Q
从通知开始服务
21
A
回答
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);
5
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是您创建的服务的服务名称。 –
相关问题
- 1. 取消通知从服务开始
- 2. 服务开始时会收到通知
- 3. 如何从服务发送额外服务(从通知报警开始)到MainActivity?
- 4. 通知从服务
- 5. 从通知开始活动
- 6. 服务不从Services.msc开始
- 7. 从Web服务开始
- 8. 从片段开始服务
- 9. 从活动开始服务
- 10. 从django服务器开始
- 11. 从活动开始服务
- 12. 开始从Windows服务
- 13. 从服务开始活动
- 14. 从COM服务EXE开始
- 15. nullpointerexception开始通知!
- 16. 从服务创建通知
- 17. 从PhoneStateListener通知服务
- 18. 通知服务通知
- 19. 从哪里开始Web服务开发?
- 20. Android开发 - 从服务开始活动
- 21. 通知服务
- 22. 如何不从通知开始活动
- 23. 服务通知打开主要活动
- 24. 从BroadcastReceiver开始从事服务活动
- 25. 从WCF服务开始。从哪儿开始?
- 26. 如何从Web服务器开始开发短信服务?
- 27. Windows服务始终“开始”
- 28. 开始web服务
- 29. 服务未开始
- 30. android开始服务
这绝对应该是被接受的答案! “PendingIntent.getService而不是pendingIntent.getActivity”是正确的做法! – Christian
@keide如何在通知中使用pendingIntent暂停服务。我们需要调用服务类的停止方法。 –
当我开始如上所述的服务时,我得到一个运行时异常:Thread [<1> main](Suspended(exception RuntimeException)) - - ActivityThread.handleCreateService(ActivityThread $ CreateServiceData)line:2561 - ActivityThread .access $ 1600(ActivityThread,ActivityThread $ CreateServiceData)行:141 –
samo