从BroadcastReceiver启动服务

Sam*_*uel 63 android broadcastreceiver

我有一个ServiceBroadcastReceiver我的应用程序,但我如何直接从该服务启动BroadcastReceiver?运用

startService(new Intent(this, MyService.class));
Run Code Online (Sandbox Code Playgroud)

BroadcastReceiver任何想法都不起作用?

编辑:

context.startService(..);

工作,我忘了上下文部分

Sam*_*uel 101

别忘了

context.startService(..);

  • 完美答案.得到它修复,阅读时很少. (2认同)
  • 这非常有帮助. (2认同)

Zee*_*v G 56

应该是这样的:

Intent i = new Intent(context, YourServiceName.class);
context.startService(i);
Run Code Online (Sandbox Code Playgroud)

一定要将服务添加到manifest.xml


Sac*_*n K 8

使用BroadcastReceivercontextonReceive方法启动服务组件.

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


ARU*_*RUN 5

最佳实践 :

虽然特别是在开始时创建一个意图BroadcastReceiver,但不要将作为上下文.就拿context.getApplicationContext()像下面

 Intent intent = new Intent(context.getApplicationContext(), classNAME);
context.getApplicationContext().startService(intent);
Run Code Online (Sandbox Code Playgroud)

  • 原因:只要注册上下文有效,上下文注册接收器就会接收广播。例如,如果您在 Activity 上下文中注册,只要该 Activity 未被销毁,您就会收到广播。如果您注册到应用程序上下文,只要应用程序正在运行,您就会收到广播。 (2认同)