从BroadcastReceiver启动服务
我的应用程序中有一个服务和广播接收器,但是如何直接从广播接收器启动服务? 运用
startService(new Intent(this, MyService.class)); 在广播接收机不工作,有什么想法?
谢谢!
编辑:
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启动时创build一个意图,不要把这作为上下文。 采取context.getApplicationContext()如下 
  Intent intent = new Intent(context.getApplicationContext(), classNAME); context.getApplicationContext().startService(intent);