In the process of Android development, WIFI that we often use will not be connected by default during sleep. How can we solve this problem when we need to maintain the connection?
Many people say that they can set the connection to sleep and maintain the connection in the advanced Wi-Fi options set by the system. This method is indeed feasible and is easy for developers to do, however, users generally do not know this setting. What should they do at this time? You can use the following code to solve the problem:
[Java]
Public void WifiNeverDormancy (Context mContext)
{
ContentResolver resolver = mContext. getContentResolver ();
Int value = Settings. System. getInt (resolver, Settings. System. WIFI_SLEEP_POLICY, Settings. System. WIFI_SLEEP_POLICY_DEFAULT );
Final SharedPreferences prefs = PreferenceManager. getdefasharsharedpreferences (mContext );
Editor editor = prefs. edit ();
Editor. putInt (mContext. getString (R. string. wifi_sleep_policy_default), value );
Editor. commit ();
If (Settings. System. WIFI_SLEEP_POLICY_NEVER! = Value)
{
Settings. System. putInt (resolver, Settings. System. WIFI_SLEEP_POLICY, Settings. System. WIFI_SLEEP_POLICY_NEVER );
}
System. out. println ("wifi value:" + value );
}
Public void WifiNeverDormancy (Context mContext)
{
ContentResolver resolver = mContext. getContentResolver ();
Int value = Settings. System. getInt (resolver, Settings. System. WIFI_SLEEP_POLICY, Settings. System. WIFI_SLEEP_POLICY_DEFAULT );
Final SharedPreferences prefs = PreferenceManager. getdefasharsharedpreferences (mContext );
Editor editor = prefs. edit ();
Editor. putInt (mContext. getString (R. string. wifi_sleep_policy_default), value );
Editor. commit ();
If (Settings. System. WIFI_SLEEP_POLICY_NEVER! = Value)
{
Settings. System. putInt (resolver, Settings. System. WIFI_SLEEP_POLICY, Settings. System. WIFI_SLEEP_POLICY_NEVER );
}
System. out. println ("wifi value:" + value );
} The above function will automatically modify the advanced options in our WIFI settings and set them to keep the connection. You can solve this problem without using other controls.
Note that this function must be declared in AndroidManifest. xml when called.
<Uses-permission android: name = "android. permission. WRITE_SETTINGS"/>