我有一个类似的场景 - 我被闹钟吵醒,闹钟的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 锁,所以一切都很好(也很丑陋)