设置Android设备WIFI在休眠时永不断开的代码实现

MainActivity如下:

package cc.ab;

import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
/**
 * Demo描述:
 * 设置设备在睡眠期间始终保持WLAN开启.
 * 
 * 参考资料:
 * 1 http://stackoverflow.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原本的策略,待我们的逻辑完成后再还原回去为好.