code

BroadcastReceiver 대 WakefulBroadcastReceiver

codestyles 2020. 12. 1. 08:03
반응형

BroadcastReceiver 대 WakefulBroadcastReceiver


누군가 BroadcastReceiver의 정확한 차이점을 설명 할 수 있습니까 WakefulBroadcastReceiver?

어떤 상황에서 각 Receiver 클래스를 사용해야합니까?


사이에 하나의 차이가 BroadcastReceiver하고 WakefulBroadcastReceiver.

브로드 캐스트 인사이드 onReceive()메소드 를 받으면

예,

BroadcastReceiver :

  • 됩니다 보장되지 것을 CPU가 깨어있을 것입니다 당신이 어떤 장기 실행 프로세스를 시작합니다. CPU가 즉시 절전 모드로 돌아갈 수 있습니다.

WakefulBroadcastReceiver :

  • 됩니다 보장 하는 것이 CPU가 깨어있을 것입니다 당신이 해고 될 때까지 completeWakefulIntent.

예:

여기에서 브로드 캐스트를 수신하면 서비스를 시작하는 것입니다.을 사용 하고 있으므로 서비스 내부에서 작업을 완료하고 실행될 때까지 CPU를 WakefulBroadcastReceiver보류 wakelock하고 절전 모드로 두지 않습니다.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);
    }
}

참고 URL : https://stackoverflow.com/questions/26380534/broadcastreceiver-vs-wakefulbroadcastreceiver

반응형