2011-01-09 95 views
52

我在我的應用程序中有一個服務和廣播接收器,但是如何直接從廣播接收器啓動服務?使用從BroadcastReceiver啓動服務

startService(new Intent(this, MyService.class)); 

在廣播接收器中不起作用,有什麼想法?

謝謝!

編輯:

context.startService(..);

作品,我忘了上下文部分

回答

84

不要忘記

context.startService(..);

+2

完美答案。讀了很少麻煩就修好了。 – Pachonk 2014-03-25 22:18:40

+1

也請查看此鏈接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

51

應該是這樣的:

Intent i = new Intent(context, YourServiceName.class); 
context.startService(i); 

一定要加對馬的服務nifest.xml

2

最佳實踐:

在創建特別是在從BroadcastReceiver出發,意圖不採取作爲背景。 採取context.getApplicationContext()像下面

Intent intent = new Intent(context.getApplicationContext(), classNAME); 
context.getApplicationContext().startService(intent); 
4

使用contextBroadcastReceiveronReceive方法來啓動你的服務組件。

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