从通知开始服务

Ale*_*gel 28 service notifications android

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

我已经通过在通知意图中包含有效服务来测试它,但没有任何反应.

Kje*_*ide 75

可以从通知中启动服务.

您必须使用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);
Run Code Online (Sandbox Code Playgroud)

  • 这肯定应该是公认的答案!"PendingIntent.getService而不是pendingIntent.getActivity"是正确的方法! (3认同)

Pla*_*lov 5

创建广播接收器,从通知接收消息,然后启动服务.