2014-11-06 107 views
0

我想在BroadcastReceiver(BOOT_COMPLETED)中啓動服務並通知它。 想要這樣:BroadcastReceiver->服務 - >通知

public class AutoLoad extends BroadcastReceiver { 
     @Override 
     public void onReceive(Context context, Intent arg1) { 
      Intent i = new Intent(context, MyService.class); 
      i.putExtra("screen_state", false); 
      context.startService(i); 
     } 
    } 

public class MyService extends Service { 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Notification notification = new   
    NotificationCompat.Builder(getApplicationContext()).setContentTitle("New mail from ").setContentText("Text") 
      .setSmallIcon(android.R.drawable.btn_plus).build(); // addAction 
     NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); 
     nm.notify(0, notification); 
     return Service.START_STICKY; 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

但是沒有通知我可以看到。請幫忙!

+0

你不需要'Service'來產生'Notification' - 你現有的代碼可以直接在'onReceive()'中。你也在泄漏你的服務,這將嚴重刺激用戶。除此之外,你有沒有一個活動,並讓你運行它?否則,您的清單註冊的接收器將無法工作。 – CommonsWare 2014-11-06 12:33:23

+0

你可以發佈清單 – 2014-11-06 12:37:56

+0

爲什麼你要這樣做,但是你可以顯示來自onReceive()的通知消息。你能解釋爲什麼你需要這個嗎? – samsad 2014-11-06 13:04:17

回答

0

您將需要一個Activity並運行它至少一次爲了能夠註冊到BOOT_COMPLETED意圖。

+0

這是真的嗎?無法通過BroadcastReceiver啓動我的服務而不啓動Activity? – user2251607 2014-11-06 16:22:17