MainActivity如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package cc.ab;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
/**
* Demo描述:
* 设置设备在睡眠期间始终保持WLAN开启.
*
* 参考资料:
* 1 http://*.com/questions/8652031/how-to-modify-wi-fi-sleep-policy-programmatically/8655070#8655070
* 2 http://blog.csdn.net/mrlixirong/article/details/24938637
* Thank you very much
*
* 注意事项:
* 1 这里使用的是android.provider.Settings.System.WIFI_SLEEP_POLICY
* 而不是Settings.System.WIFI_SLEEP_POLICY!!!!!!!!!!!!!!!!!!!!!!!
*
* 2 权限<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
*
* 3 在实际项目中,这么强制性地设置WIFI在休眠时永不断开有些粗鲁了.
* 可以先记录下WIFI原本的策略,待我们的逻辑完成后再还原回去为好.
*/
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原本的策略,待我们的逻辑完成后再还原回去为好.