Sam*_*uel 63 android broadcastreceiver
我有一个Service和BroadcastReceiver我的应用程序,但我如何直接从该服务启动BroadcastReceiver?运用
startService(new Intent(this, MyService.class));
Run Code Online (Sandbox Code Playgroud)
BroadcastReceiver任何想法都不起作用?
编辑:
context.startService(..);
工作,我忘了上下文部分
Zee*_*v G 56
应该是这样的:
Intent i = new Intent(context, YourServiceName.class);
context.startService(i);
Run Code Online (Sandbox Code Playgroud)
一定要将服务添加到manifest.xml
使用BroadcastReceivercontext的onReceive方法启动服务组件.
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, YourService.class);
context.startService(serviceIntent);
}
Run Code Online (Sandbox Code Playgroud)
最佳实践 :
虽然特别是在开始时创建一个意图BroadcastReceiver,但不要将其作为上下文.就拿context.getApplicationContext()像下面
Intent intent = new Intent(context.getApplicationContext(), classNAME);
context.getApplicationContext().startService(intent);
Run Code Online (Sandbox Code Playgroud)