通过通知意图发送putExtra

时间:2015-05-26 14:06:24

标签: android

我想根据代码打开一个特定的标签。如果我通过普通按钮执行此操作,则可以正常工作。

它的工作方式:

public void toSomewhere (View view) {
    Intent intent = new Intent(this, SomewhereActivity.class);
    intent.putExtra("FirstTab", 2);
    startActivity(intent);
}

Intent i = getIntent();
int tabToOpen = i.getIntExtra("FirstTab", -1);
if (tabToOpen!=-1) {
    // Open the right tab
}
else {
    // Other tab
}

我希望它通过通知的方式(此时我有这个代码发送通知,但不通过.putExtra):

public static void NotificationIntent(String title, String message) {
    Intent notificationIntent = new Intent(currentContext, SomewhereActivity.class);
    **notificationIntent.putExtra("FirstTab", 2);**
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(currentContext, 0, notificationIntent, 0);

    NotificationCompat.Builder mBuilder = new    NotificationCompat.Builder(currentContext)
            .setContentTitle(title)
            .setContentIntent(intent)
            .setContentText(message)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
    NotificationManager mNotificationManager = (NotificationManager) currentContext.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());
}

有没有人知道如何解决这个问题,所以它也适用于通知帖子?

1 个答案:

答案 0 :(得分:3)

使用FLAG_UPDATE_CURRENT

来自docs:

  

指示如果描述的PendingIntent已经存在的标志,则保留它,但将其额外数据替换为此新Intent中的内容。用于getActivity(Context,int,Intent,int),getBroadcast(Context,int,Intent,int)和getService(Context,int,Intent,int)。

     

如果您要创建只有额外内容更改的意图,并且不关心接收到您之前的PendingIntent的任何实体将能够使用您的新附加功能启动它,即使未明确指定它们也可以使用它。

代码:

Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class);
notificationIntent.putExtra("NotificationMessage", notificationMessage);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);

onNewIntent方法的活动中:

@Override
public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    String notificationMessage = extras.getString("NotificationMessage", "UNDEFINED");
}

也可以转发onCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    onNewIntent(getIntent());
}