2011-06-21 103 views
21

是否可以从通知开始服务? 开始一项活动的正常方式是完美的,但在实际启动应用程序之前,我需要对数据进行一些预先检查。从通知开始服务

我已经在通知意图中包含了一个有效的服务来测试它,但没有任何反应。

回答

65

可以从通知开始服务。

您必须使用PendingIntent.getService而不是pendingIntent.getActivity。

Intent notificationIntent = new Intent(mContext, HandleNotificationClickService.class); 
PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, notificationIntent, 0); 

Notification notification = new Notification(icon, tickerText,System.currentTimeMillis()); 
notification.setLatestEventInfo(mContext,contentTitle , contentText, pendingIntent); 
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT; 

NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); 

notificationManager.notify(CALLER_ID_NOTIFICATION_ID, notification); 
+3

这绝对应该是被接受的答案! “PendingIntent.getService而不是pendingIntent.getActivity”是正确的做法! – Christian

+0

@keide如何在通知中使用pendingIntent暂停服务。我们需要调用服务类的停止方法。 –

+0

当我开始如上所述的服务时,我得到一个运行时异常:Thread [<1> main](Suspended(exception RuntimeException)) - - ActivityThread.handleCreateService(ActivityThread $ CreateServiceData)line:2561 - ActivityThread .access $ 1600(ActivityThread,ActivityThread $ CreateServiceData)行:141 – samo

5

创建一个广播接收器,接收来自通知的消息,然后启动该服务。

+0

感谢您与广播接收器的TIPP。可以把所有的检查,所以我不需要该服务了。 – AlexVogel

1
private void createNotification(String message) 

{ 

    Intent intent = new Intent(this, Yourservice.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    PendingIntent pendingIntent = PendingIntent.getService(this, 0 /* Request code */, intent, 
     0); 

    NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) 
     .setSmallIcon(R.drawable.icond) 
     .setContentTitle("Start Launcher") 
     .setContentText(message) 
     .setAutoCancel(true) 
     .setOngoing(true) 
     .setWhen(System.currentTimeMillis()) 
     .setContentIntent(pendingIntent); 

    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); 

    notificationManager.notify(ID_NOTIFICATION , notificationBuilder.build()); 

} 
+3

也添加说明 –

+0

只是在方法中调用您的消息字符串调用此createNotification(“test”);和.setContentTitle(“Start Launcher”)是您的通知标题Yourservice.class是您创建的服务的服务名称。 –