有人可以解释一下两者之间的确切区别是什么BroadcastReceiver https://developer.android.com/reference/android/content/BroadcastReceiver.html and WakefulBroadcastReceiver https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html?
在什么情况下我们必须使用每个 Receiver 类?
两者之间只有一处区别BroadcastReceiver
and WakefulBroadcastReceiver
.
当你收到里面的广播时onReceive()
method,
认为,
广播接收器 :
- It is 不保证 that CPU将保持唤醒状态如果您启动一些长时间运行的进程。 CPU 可能会立即返回睡眠状态。
唤醒广播接收器 :
- It is 保证 that CPU将保持唤醒状态直到你开火
completeWakefulIntent
.
Example:
在这里,当您接收广播时,您正在启动一项服务,就像您正在使用的一样WakefulBroadcastReceiver
,它将保持wakelock
并且不会让 CPU 休眠,直到您完成服务内的工作并启动completeWakefulIntent
Code:
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)