1

我正在使用唤醒锁作为警报来定期更新应用程序状态。wifi 需要一段时间才能在三星手机上连接。此外,Wifi 上的“保持清醒”选项不适用于三星手机(他们也没有兴趣解决这个问题)。所以当wakelock确实发生时,它应该等待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 中的 Web 服务调用将失败。无论如何,我将不得不释放锁。

所以

我应该放入 wifi/数据连接侦听器吗?或者,还有更好的方法 ?

4

1 回答 1

1

我有一个类似的场景 - 我被闹钟吵醒,闹钟的BroadcastReceiver启动WakefulIntentService并且服务开始扫描网络。我用一种愚蠢的方式来抓住锁1 - 我打算用闩锁代替它。我建议你用WakefulIntentService替换“AsyncTask” 。AsyncTask 很有可能永远不会被触发。在WakefulIntentService 中,您必须获得并持有一个 wifi 锁 - 我会将其设为 YourWakefulIntentService 的静态字段 - 对此并不完全清楚 - 这是一段时间前的事了。如果这不起作用,我会在 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:这是一个工人阶级——我只是使用第二个唤醒意图服务来保持唤醒锁——仍然需要重构它以使用锁存器,但这种方法至少有效(我有第二个服务(Gatekeeper)在监视器上等待并在 Gatekeeper 内设置唤醒锁。 Gatekeeper 还持有它的 CPU 锁,所以一切都很好(也很丑陋)

于 2013-10-15T14:50:02.547 回答