我使用唤醒锁作为警报来定期更新应用程序状态。三星手机上的 WiFi 需要一段时间才能连接。还有 Wifi 上的“保持唤醒”选项does not在三星手机上工作(他们也没有兴趣解决这个问题)。因此,当唤醒锁确实发生时,它应该等待 wifi 连接。我是否需要为 wifi 连接创建一个侦听器才能使其工作,或者应该唤醒锁,有点阻止该 wifi 连接?
mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "Taxeeta");
mWakeLock.acquire();
// do some network activity, in a asynctask
// in the doPost of asyscTask, release lock
编辑 :
问题是,在AsyncTask中如果网络未连接,或者需要时间才能上网(3g需要一段时间才能上网),Async doInBackground中的webservice调用将会失败。无论如何我都必须释放锁。
SO
我应该放入 wifi/数据连接侦听器吗?或者,还有更好的方法 ?
I have a similar scenario - I am woken up by an alarm, the alarm's BroadcastReceiver launches a WakefulIntentService and the service starts a scan for networks. I use a stupid way of holding on to the lock1 - I intend to replace this with a latch. I suggest you replace the "AsyncTask" with a WakefulIntentService. Chances are the AsyncTask is not ever fired. In the WakefulIntentService you must acquire and hold on to a wifi lock - I would make this a static field of the YourWakefulIntentService - not entirely clear on this - it's a while back. If this does not work I would use a latch in the YourWakefulIntentService :
// register an alarm
Intent i = new Intent(context, YourReceiver.class);
PendingIntent alarmPendingIntent= PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
public class YourReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
WakefulIntentService.sendWakefulWork(context, YourWIS.class);
}
}
//pseudocode !
public class YourWIS extends WakefulIntentService { // you must add a cstor !
@Override
doWakefulWork() {
acquireWifiLock();
enableScanReceiver();
startScan();
serviceLatch.wait();
releaseWifiLock();
}
}
// in YourScanReceiver
onReceive() {
if(action.equals(SCAN_RESULTS) {
// do something that does not take time or start another/the same
// WakefulIntentService
serviceLatch.notify();
}
}
首先尝试 WakefulIntentService(我猜您从警报接收器启动 AsyncTask)。扫描接收器是注册用于接收扫描结果的接收器(请参阅 WifiManager 文档 - 对于睡眠问题,更喜欢接收器而不是侦听器)
1 : this is a working class - I just use a second wakeful intent service to keep the wake locks - have still to refactor it to use latches but this approach at least works (I have the second service (the Gatekeeper) wait on a monitor and have the wake lock inside the Gatekeeper. The gatekeeper also holds its CPU lock so all is fine (and ugly)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)