MainActivity如下:
package cc.ab;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setWifiNeverSleep();
}
private void setWifiNeverSleep(){
int wifiSleepPolicy=0;
wifiSleepPolicy=Settings.System.getInt(getContentResolver(),
android.provider.Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
System.out.println("---> 修改前的Wifi休眠策略值 WIFI_SLEEP_POLICY="+wifiSleepPolicy);
Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
wifiSleepPolicy=Settings.System.getInt(getContentResolver(),
android.provider.Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
System.out.println("---> 修改后的Wifi休眠策略值 WIFI_SLEEP_POLICY="+wifiSleepPolicy);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
代码如上,不过在实际项目中,这么强制性地设置WIFI在休眠时永不断开有些粗鲁了.
可以先记录下WIFI原本的策略,待我们的逻辑完成后再还原回去为好.