我正在使用带有各种 标签 的 Activitiy 。从应用程序的不同部分,创建通知以告诉用户某些事情发生了变化。当用户点击 通知 时,我现在设法调用 Activity 。但是,我如何确定 Activity 是在运行时以“正常”方式创建还是通过单击通知来创建?
(根据点击的通知,我想转发到另一个选项卡而不是显示主选项卡。)
Intent intent = new Intent(ctx, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);
// TODO: Replace with .Build() for api >= 16
Notification noti = new Notification.Builder(ctx)
.setContentTitle("Notification"
.setContentText(this.getName())
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setDefaults(
Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS)
.setAutoCancel(true)
.getNotification();
NotificationManager notificationManager = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
// Hide the notification after its selected
notificationManager.notify(this.getId(), noti);
这成功地调用了我的 MainActivity。但是当 Activity 被
pendingIntent
触发时是否有一些方法被调用?想在 Main Activity 中定义类似的东西:
onTriggeredByNotification(Notification noti){
//determinte tab, depending on Notification.
}
最佳答案
从通知传递一个 bool 值,并在 Activity 的onCreate方法中检查该值。
Intent intent = new Intent(ctx, MainActivity.class);
intent.putExtra("fromNotification", true);
...
if (getIntent().getExtras() != null) {
Bundle b = getIntent().getExtras();
boolean cameFromNotification = b.getBoolean("fromNotification");
}