【发布时间】:2015-09-07 11:20:06
【问题描述】:
我一直在通过这个链接学习 WakefulBroadcastReceiver:https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html
我对此有一些困惑:
- 此接收器是否确保即使设备处于睡眠模式也能接收到广播? (我认为不,它只是在接收到广播后保持设备唤醒,直到调用 completeWakefulIntent()。)
- 文档说明了在接收器中使用意图服务,并在工作完成后调用 completeWakefulIntent。
代码:
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
@Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock. This sample just does some slow work,
// but more complicated implementations could take their own wake
// lock here before releasing the receiver's.
//
// Note that when using this approach you should be aware that if your
// service gets killed and restarted while in the middle of such work
// (so the Intent gets re-delivered to perform the work again), it will
// at that point no longer be holding a wake lock since we are depending
// on SimpleWakefulReceiver to that for us. If this is a concern, you can
// acquire a separate wake lock here.
for (int i=0; i<5; i++) {
Log.i("SimpleWakefulReceiver", "Running service " + (i+1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
}
现在,正如文档所说,这个接收器持有唤醒锁,我非常怀疑从接收器启动类似意图服务的东西是否是一种好习惯。这将阻止接收器释放唤醒锁并消耗大量电池,因为服务通常用于长时间操作。
即使上面的代码 sn-p 突出显示,在释放锁之前也有 25 秒的延迟。这是使用此接收器的正确方法还是应该仅用于短期操作?任何帮助表示赞赏。
【问题讨论】:
-
我不是一个完美的人,说它是好是坏,但它很完美
-
基本上没有对接收器本身的引用......它只是开始为意图持有锁......并且 static 方法释放锁......
-
@Selvin 即使没有参考(我的意思是你建议的静态方法),仍然有一个唤醒锁,这无论如何都会耗尽电池?
-
你能不能详细点,没明白你的意思 ...为什么... WakefulBroadcastReceiver的来源非常简单... 还有一个保持唤醒锁,这无论如何都会耗尽电池? ...这就是为什么有 completeWakefulIntent 方法
-
@Selvin 间接我的问题是:在长时间运行的服务中是否需要唤醒锁,如果它不会耗尽电池电量?您可以根据代码中的此注释忽略接收器:此时 SimpleWakefulReceiver 仍在为我们持有唤醒锁。我们可以在这里做任何我们需要做的事情,然后告诉它它可以释放唤醒锁。这个示例只是做了一些缓慢的工作,但更复杂的实现可以在释放接收器之前在这里使用自己的唤醒锁。
标签: android broadcastreceiver android-wake-lock