Android 休眠导致的问题Socket断开

来源:互联网 发布:淘宝网棒球帽 编辑:程序博客网 时间:2024/04/28 19:06

开发过程中,发现手机锁屏/休眠会导致通信有问题。调试后发现是socket断开了,这是与wifi有关系,而wifi的问题又与手机休眠有关。


1.可以手动设置

设置——无线和网络——WLAN——高级设定——睡眠期间保持WLAN开启——总是

然而,并不是所以有手机都有这个设置,因为有些系统被开发商定制(阄割)了。

2.代码设置

[java] view plain copy
  1. public void setWifiDormancy(Context context){  
  2.         int value = Settings.System.getInt(context.getContentResolver(), Settings.System.WIFI_SLEEP_POLICY,  Settings.System.WIFI_SLEEP_POLICY_DEFAULT);  
  3.         Log.d(TAG, "setWifiDormancy() returned: " + value);  
  4.         final SharedPreferences prefs = context.getSharedPreferences("wifi_sleep_policy", Context.MODE_PRIVATE);  
  5.         SharedPreferences.Editor editor = prefs.edit();  
  6.         editor.putInt(ConfigManager.WIFI_SLEEP_POLICY, value);  
  7.         editor.commit();  
  8.   
  9.         if(Settings.System.WIFI_SLEEP_POLICY_NEVER != value){  
  10.             Settings.System.putInt(context.getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER);  
  11.         }  
  12.     }  
[java] view plain copy
  1. //恢复  
[java] view plain copy
  1. public void restoreWifiDormancy(Context context){  
  2.         final SharedPreferences prefs = context.getSharedPreferences("wifi_sleep_policy", Context.MODE_PRIVATE);  
  3.         int defaultPolicy = prefs.getInt(ConfigManager.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);  
  4.         Settings.System.putInt(context.getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, defaultPolicy);  
  5.     }  
加权限:<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

ref:http://blog.csdn.net/mrlixirong/article/details/24938637


然而,对我的应用却无效 。上述文章作者最后使用service解决了“当采用Service时,网络连接就持续保持顺畅了。而且不管WIFI休眠政策设置如何,黑屏以后都可以保持联网”。下次有时间再验证这种方法。


3.在2的基础上,结合PowerManager使用。

[html] view plain copy
  1. PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);  
  2.  PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");  
  3.  wl.acquire();  
  4.    ..screen will stay on during this section..  
  5.  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

0 0
原创粉丝点击