IT TIP

BroadcastReceiver에서 서비스 시작

itqueen 2020. 11. 22. 21:03
반응형

BroadcastReceiver에서 서비스 시작


나는이 ServiceBroadcastReceiver내 응용 프로그램에서,하지만 내가 어떻게에서 직접 서비스를 시작합니까 BroadcastReceiver? 사용

startService(new Intent(this, MyService.class));

BroadcastReceiver, 어떤 아이디어 에서 작동하지 않습니까?

편집하다:

context.startService (..);

작동, 컨텍스트 부분을 잊었습니다.


잊지 마세요

context.startService(..);


다음과 같아야합니다.

Intent i = new Intent(context, YourServiceName.class);
context.startService(i);

manifest.xml에 서비스를 추가해야합니다.


서비스 구성 요소를 시작하려면 BroadcastReceiver 메서드 context에서를 사용하십시오 .onReceive

@Override
public void onReceive(Context context, Intent intent) {
      Intent serviceIntent = new Intent(context, YourService.class);
      context.startService(serviceIntent);
}

모범 사례 :

특히에서 시작하는 동안 인 텐트를 만드는 동안 이것을 컨텍스트로 BroadcastReceiver받아들이지 마십시오. 받아 아래와 같이context.getApplicationContext()

 Intent intent = new Intent(context.getApplicationContext(), classNAME);
context.getApplicationContext().startService(intent);

 try {
        Intent intentService = new Intent(context, MyNewIntentService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intentService );
        } else {
            context.startService(intentService );
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

수신자의 onReceive (Context, Intent) 메소드는 메인 스레드에서 실행되기 때문에 빠르게 실행되고 반환되어야합니다. 오래 실행되는 작업을 수행해야하는 경우에는 onReceive ()가 반환 된 후 시스템이 전체 프로세스를 종료 할 수 있으므로 스레드 생성 또는 백그라운드 서비스 시작에주의하십시오. 자세한 내용은 프로세스 상태에 대한 영향을 참조하십시오. 장기 실행 작업을 수행하려면 다음을 권장합니다.

수신자의 onReceive () 메서드에서 goAsync ()를 호출하고 BroadcastReceiver.PendingResult를 백그라운드 스레드에 전달합니다. 이렇게하면 onReceive ()에서 돌아온 후에도 브로드 캐스트가 활성화됩니다. 그러나이 접근 방식을 사용하더라도 시스템은 브로드 캐스트를 매우 빠르게 (10 초 미만) 완료 할 것으로 예상합니다. 메인 스레드의 결함을 방지하기 위해 작업을 다른 스레드로 이동할 수 있습니다. JobScheduler developer.android.com 으로 작업 예약

참고 URL : https://stackoverflow.com/questions/4641712/starting-service-from-broadcastreceiver

반응형