广播接收器vs唤醒广播接收器

广播接收器vs唤醒广播接收器,第1张

广播接收器vs唤醒广播接收器

BroadcastReceiver
和之间只有一个区别
WakefulBroadcastReceiver

当您收到内部广播

onReceive()
方法时,

假设,

BroadcastReceiver

  • 不保证CPU将保持清醒 ,如果你启动一些长时间运行的进程。CPU可能会立即回到睡眠状态。

WakefulBroadcastReceiver

  • 这是 保证CPU将保持清醒 ,直到你开除
    completeWakefulIntent

例:

在这里,当您接收广播时,即表示您正在使用的方式启动一项服务,直到您完成服务中的工作并触发后

WakefulBroadcastReceiver
,它将保持
wakelock
并且不会让CPU进入睡眠状态
completeWakefulIntent

码:

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);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5615509.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存