gpt4 book ai didi

android - 确定 Activity 是否被通知调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:10:01 24 4
gpt4 key购买 nike

我正在使用一个带有各种标签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");
}

关于android - 确定 Activity 是否被通知调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14122085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com