2014-11-06 49 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