开发过程中,发现手机锁屏/休眠会导致通信有问题。调试后发现是socket断开了,这是与wifi有关系,而wifi的问题又与手机休眠有关。
1.可以手动设置
设置——无线和网络——WLAN——高级设定——睡眠期间保持WLAN开启——总是
然而,并不是所以有手机都有这个设置,因为有些系统被开发商定制(阄割)了。
2.代码设置
- public void setWifiDormancy(Context context){
- int value = Settings.System.getInt(context.getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
- Log.d(TAG, "setWifiDormancy() returned: " + value);
- final SharedPreferences prefs = context.getSharedPreferences("wifi_sleep_policy", Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = prefs.edit();
- editor.putInt(ConfigManager.WIFI_SLEEP_POLICY, value);
- editor.commit();
- if(Settings.System.WIFI_SLEEP_POLICY_NEVER != value){
- Settings.System.putInt(context.getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER);
- }
- }
- //恢复
- public void restoreWifiDormancy(Context context){
- final SharedPreferences prefs = context.getSharedPreferences("wifi_sleep_policy", Context.MODE_PRIVATE);
- int defaultPolicy = prefs.getInt(ConfigManager.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
- Settings.System.putInt(context.getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, defaultPolicy);
- }
ref:http://blog.csdn.net/mrlixirong/article/details/24938637
然而,对我的应用却无效 。上述文章作者最后使用service解决了“当采用Service时,网络连接就持续保持顺畅了。而且不管WIFI休眠政策设置如何,黑屏以后都可以保持联网”。下次有时间再验证这种方法。
3.在2的基础上,结合PowerManager使用。
- PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
- PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
- wl.acquire();
- ..screen will stay on during this section..
- wl.release();
因为app使用activity,故在oncreate中wl.acquire();,在ondestroy中wl.release();
加权限: android.permission.WAKE_LOCK问题到此暂时解决。
ref:http://stackoverflow.com/questions/22025888/keeping-wifi-connection-on-when-android-mobile-sleeps
来自:http://blog.csdn.net/hhbgk/article/details/49997291