BroadcastReceiver与WakefulBroadcastReceiver

use*_*111 61 java android broadcastreceiver wakelock

有人可以解释一下BroadcastReceiver和之间的确切区别WakefulBroadcastReceiver吗?

在什么情况下我们必须使用每个Receiver类?

Meh*_*sar 106

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @TheHunter:手机运行CPU(中央处理器)中的所有进程.计算机确实有像Intel i3,i5等CPU,手机也有像snapdragon这样的CPU.为了节省能源,每当手机变得理想时,用户不进行交互,显示灯关闭,CPU可能进入理想(睡眠)模式而不是处理事物. (6认同)
  • 虽然上面的答案是正确的,但我还想添加一些输入.与唤醒广播接收器一起使用的意图服务应仅用于短操作(我可能错了,在这种情况下我需要一些更正),因为接收器保持唤醒锁定直到工作完成.长时间保持唤醒锁可能导致电池严重耗尽,应尽可能避免. (2认同)
  • WakefulBroadcastReceiver 在 Android O 上已弃用:https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html (2认同)