Starting Service from BroadcastReceiver

谁都会走 提交于 2019-11-29 02:01:39

问题


I have a Service and BroadcastReceiver in my application, but how do I launch the service directly from the BroadcastReceiver? Using

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

does not work in a BroadcastReceiver, any ideas?

EDIT:

context.startService(..);

works, I forgot the context part


回答1:


Don't forget

context.startService(..);




回答2:


should be like that:

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

be sure to add the service to manifest.xml




回答3:


use the context from the onReceive method of your BroadcastReceiver to start your service component.

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



回答4:


Best Practice :

While creating an intent especially while starting from BroadcastReceiver, dont take this as context. Take context.getApplicationContext() like below

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



回答5:


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



回答6:


Because a receiver's onReceive(Context, Intent) method runs on the main thread, it should execute and return quickly. If you need to perform long running work, be careful about spawning threads or starting background services because the system can kill the entire process after onReceive() returns. For more information, see Effect on process state To perform long running work, we recommend:

Calling goAsync() in your receiver's onReceive() method and passing the BroadcastReceiver.PendingResult to a background thread. This keeps the broadcast active after returning from onReceive(). However, even with this approach the system expects you to finish with the broadcast very quickly (under 10 seconds). It does allow you to move work to another thread to avoid glitching the main thread. Scheduling a job with the JobScheduler developer.android.com



来源:https://stackoverflow.com/questions/4641712/starting-service-from-broadcastreceiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!