【问题标题】:wakeLock does not wait for network connectivitywakeLock 不等待网络连接
【发布时间】:2013-10-22 00:55:20
【问题描述】:

我正在使用唤醒锁作为闹钟来定期更新应用状态。 wifi 需要一段时间才能在三星手机上连接。此外,Wifi 上的“保持清醒”选项无法在三星手机上运行 (nor are they interested in fixing the issue)。所以当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/数据连接监听器放进去吗?还是有更好的办法?

【问题讨论】:

  • 为什么要“wakeLock 等待网络连接”??您必须持有唤醒锁,并确保在网络连接时一直持有它。发布更多您的设计以获得正确的答案
  • 你的问题解决了吗?

标签: android-wifi 3g android-wake-lock


【解决方案1】:

我有类似的情况 - 我被警报吵醒,the alarm's BroadcastReceiver 启动 WakefulIntentService 并且服务开始扫描网络。 I use a stupid way of holding on to the lock1 - 我打算用闩锁代替它。我建议您将“AsyncTask”替换为WakefulIntentService。 AsyncTask 很有可能永远不会被触发。在 WakefulIntentService 中,您必须获得并持有一个 wifi 锁 - 我会将其设为 YourWakefulIntentService 的 static 字段 - 对此并不完全清楚 - 这已经有一段时间了。如果这不起作用,我会在 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 锁,所以一切都很好(也很丑)

【讨论】:

  • 这个很有用,能不能详细点分享更多代码。我不知道扫描接收器是什么。我正在阅读倒计时。
  • 好的,明白了latch的东西,很简单。去 WakefulIntentService
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
相关资源
最近更新 更多