Android 休眠导致的问题Socket断开

开发过程中,发现手机锁屏/休眠会导致通信有问题。调试后发现是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);
	}
加权限:<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

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







  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值