待通知意图不起作用

pra*_*sti 34 android android-pendingintent

下面是我的代码块,它应该NotificationActivity在点击通知时打开.但它不起作用.

private void setNotification(String notificationMessage) {
    Uri alarmSound = getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    mNotificationManager  = getApplication().getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(getApplicationContext(), NotificationActivity2.class);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
    .setSmallIcon(R.drawable.logo)
    .setContentTitle("My Notification")
    .setStyle(new NotificationCompat.BigTextStyle()
    .bigText(notificationMessage))
    .setContentText(notificationMessage).setAutoCancel(true);
    mBuilder.setSound(alarmSound);
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

}
Run Code Online (Sandbox Code Playgroud)

dro*_*idx 76

试试这个:

private void setNotification(String notificationMessage) {

//**add this line**
int requestID = (int) System.currentTimeMillis();

Uri alarmSound = getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mNotificationManager  = getApplication().getSystemService(Context.NOTIFICATION_SERVICE);

Intent notificationIntent = new Intent(getApplicationContext(), NotificationActivity2.class);

//**add this line**
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

//**edit this line to put requestID as requestCode**
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.logo)
.setContentTitle("My Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(notificationMessage))
.setContentText(notificationMessage).setAutoCancel(true);
mBuilder.setSound(alarmSound);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

}
Run Code Online (Sandbox Code Playgroud)

  • 你能说出为什么这个有用的原因......这是非常模糊的. (13认同)
  • 也为我工作过.只是传递一个不同于零的requestCode就完成了这项工作.我只是添加了标志:intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); (5认同)

pra*_*tsJ 11

您可能正在使用等于0的通知ID.已知通知ID为0的问题.如果您将使用任何其他ID,它应该可以工作.


Rav*_*udi 5

我添加了任务构建器,下面的块代码为我工作

Intent intent = new Intent(context, HomeActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(SplashActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)