Code implementation to set Android device WIFI to never disconnect when sleeping

  • 2020-06-03 08:19:28
  • OfStack

MainActivity is as follows:


package cc.ab;

import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
/**
 * Demo describe :
 *  Set the device to remain in place during sleep WLAN open .
 * 
 *  The resources :
 * 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
 *  
 *  Matters needing attention :
 * 1  This is the one that's used here android.provider.Settings.System.WIFI_SLEEP_POLICY
 *   Rather than Settings.System.WIFI_SLEEP_POLICY!!!!!!!!!!!!!!!!!!!!!!!
 *  
 * 2  permissions <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
 * 
 * 3  In a real project , This is mandatory WIFI It's a little rude to never disconnect from sleep .
 *   You can write it down first WIFI Original strategy , It is better to revert back after our logic is complete .
 */
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("--->  Before the change Wifi Sleep strategy value  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("--->  The modified Wifi Sleep strategy value  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>

The code is as above, but in a real project, it would be rude to force WIFI to never disconnect when sleeping.
We can record the original strategy of WIFI and restore it after our logic is completed.


Related articles: