Starting Service from BroadcastReceiver

穿精又带淫゛_ 提交于 2019-11-30 04:09:29

Don't forget

context.startService(..);

should be like that:

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

be sure to add the service to manifest.xml

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

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

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

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