我在我的应用程序中有一个服务和广播接收器,但是如何直接从广播接收器启动服务?使用从BroadcastReceiver启动服务
startService(new Intent(this, MyService.class));
在广播接收器中不起作用,有什么想法?
谢谢!
编辑:
context.startService(..);
作品,我忘了上下文部分
我在我的应用程序中有一个服务和广播接收器,但是如何直接从广播接收器启动服务?使用从BroadcastReceiver启动服务
startService(new Intent(this, MyService.class));
在广播接收器中不起作用,有什么想法?
谢谢!
编辑:
context.startService(..);
作品,我忘了上下文部分
不要忘记
context.startService(..);
应该是这样的:
Intent i = new Intent(context, YourServiceName.class);
context.startService(i);
一定要加对马的服务nifest.xml
最佳实践:
在创建特别是在从BroadcastReceiver
出发,意图不采取这作为背景。 采取context.getApplicationContext()
像下面
Intent intent = new Intent(context.getApplicationContext(), classNAME);
context.getApplicationContext().startService(intent);
使用context
从BroadcastReceiver的onReceive
方法来启动你的服务组件。
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, YourService.class);
context.startService(serviceIntent);
}
完美答案。读了很少麻烦就修好了。 – Pachonk 2014-03-25 22:18:40
也请查看此链接https://groups.google.com/forum/#!topic/android-developers/WVoO8kQCFF0 context.startService(new Intent(MusicService.ACTION_PAUSE,null,context,MusicService.class)); – cwhsu 2014-11-26 06:17:28