点击通知不启动活动通知

2023-09-04 03:12:33 作者:唯恐天下不亂i

我创造从服务的通知;该通知显示,但是当我点击它,什么也没有发生。这应该打开活动

I am creating a notification from a service; the notification is shown, but when I click on it, nothing happens: It was supposed to open an activity.

我的code:

NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, "test", when);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |   Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(this, 0, 
notificationIntent,PendingIntent.FLAG_CANCEL_CURRENT);

notification.setLatestEventInfo(this, "title", "message", intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

但是,如果我用pretty的大同小异$ C $从活动的内部C,我可以点击通知,我的活动显示。我究竟做错了什么?

However if I use pretty much the same code from inside an activity, I can click on the notification, and my activity is shown. What am I doing wrong?

编辑: 事实证明,没有什么不对的code,有一个不同的问题: 当我的服务完成后,它创建了具有code以上的通知。但是,该服务也播出了它被完成,接收器创建一个通知,它使用了不同的code创建的通知(没有PendingIntents,通知被点击时,所以没有定义的动作),并且通知要已经把原有的,正确的本身,而不是。

It turns out that there was nothing wrong with this code, there was a different issue: When my service finished, it created the notification with the code above. However, the service also broadcasted that it was finished, and the receiver created another notification, which used a different code to create the notification (with no PendingIntents, so no defined action when the notification is clicked), and that notification must have placed itself instead of the original, correct one.

推荐答案

在使用Notification.Builder以上的Andr​​oid 3.0或NotificationCompat.Builder支持库V4作为@Raghunandan暗示的评论,我有同样的问题顶部一个可能的共同解决您的问题。

On top of using Notification.Builder for above Android 3.0, or NotificationCompat.Builder in support library v4 as @Raghunandan suggests in the comment, I had the same problem with a possible common solution to your problem.

这是特定于4.4,如下所示:发行63236 :与TaskStackBuilder.getPendingIntent()通知没有打开活动这里的问题61850:奇巧通知操作待定意向后,无法继续应用程序重新安装

This is specific to 4.4 as seen here:Issue 63236:Notification with TaskStackBuilder.getPendingIntent() is not open the Activity and here Issue 61850: KitKat notification action Pending Intent fails after application re-install

一个确认的解决方案是执行取消()操作上相同的PendingIntent与一个你将要创建。

One confirmed solution is to perform cancel() operation on an identical PendingIntent with the one you are about to create.

什么工作对我来说是修改目标的活动清单定义,并添加 安卓出口=真正的的中的活动标签为目标的活动。这将是MainActivity你的情况我想。

What worked for me was to modify the target Activity's manifest definition and add android:exported="true" within "activity" tags for the target Activity. That would be MainActivity in your case I assume.

例如:

<activity
        android:name="com.your.MainActivity"
        android:exported="true" >
.
.
</activity>