【发布时间】:2011-06-06 05:12:19
【问题描述】:
我的应用程序中有Service 和BroadcastReceiver,但是如何直接从BroadcastReceiver 启动服务?使用
startService(new Intent(this, MyService.class));
在BroadcastReceiver 中不起作用,有什么想法吗?
编辑:
context.startService(..);
有效,我忘记了上下文部分
【问题讨论】:
我的应用程序中有Service 和BroadcastReceiver,但是如何直接从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 的onReceive 方法中的context 来启动您的服务组件。
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, YourService.class);
context.startService(serviceIntent);
}
【讨论】:
最佳实践:
在创建意图时,尤其是从 BroadcastReceiver 开始时,不要将 this 作为上下文。
以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
【讨论】:
最好使用 ContextCompat:
Intent serviceIntent = new Intent(context, ForegroundService.class);
ContextCompat.startForegroundService(context, serviceIntent);
【讨论】: