×

WIFI高级选项中将连接设为休眠保持连接

Kalet Kalet 发表于2015-11-11 14:57:05 浏览248 评论0

抢沙发发表评论

在开发Android的过程中,我们经常用到的WIFI在休眠情况下默认是会不连接的,这个时候当我们需要保持连接时,该如何解决

        不少人说可以在系统设置的WIFI高级选项中将连接设为休眠保持连接,这个办法的确可行,对于开发者来说很容易办到,但是对于用户来说他们一般不会知道这么设置,这个时候该怎么办呢?可以使用如下代码解决

[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.getDefaultSharedPreferences(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.getDefaultSharedPreferences(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);
 }上面这个函数,会自动修改我们WIFI设置中的高级选项,将其设置为一直保持连接。不用使用其他控件就可以解决。

需要注意的是此函数在调用时必须现在AndroidManifest.xml中声明权限

 <uses-permission android:name="android.permission.WRITE_SETTINGS"/>

群贤毕至

访客