确定活动是否由通知调用 [英] Determine if Activity is called by a Notification

查看:59
本文介绍了确定活动是否由通知调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有各种标签活动.从应用程序的不同部分创建通知,以告知用户某些更改.现在,当用户点击通知时,我设法调用了活动.但是,如何确定运行时或通过单击通知以正常"方式创建活动的原因?

I am using an Activitiy with various Tabs on it. From a different part of the application, Notifications are created to tell the user that something has changed. I now managed to Call the Activity, when the user clicks on the Notification. But how can i determine wheter a Activity is created the "normal" way during runtime or by clicking on the notification?

(取决于单击的通知,我想转发到另一个选项卡,而不是显示主选项卡.)

(Depending on the notification clicked, i want to forward to another tab instead of showing the main Tab.)

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.但是pendingIntent触发Activity时是否会调用某些方法?

This successfully calls my MainActivity. But is there some Method that is called when the Activity is triggered by the pendingIntent?

要在主要活动中定义类似的内容:

Thought about to define something like this in the Main Activity:

onTriggeredByNotification(Notification noti){
     //determinte tab, depending on Notification.
}

推荐答案

从通知中传递布尔值,并在活动的onCreate方法中检查该值.

Pass a boolean value from notification and check for the same in the onCreate method of the activity.

 Intent intent = new Intent(ctx, MainActivity.class);
 intent.putExtra("fromNotification", true);

...

if (getIntent().getExtras() != null) {
  Bundle b = getIntent().getExtras();
  boolean cameFromNotification = b.getBoolean("fromNotification");
}

这篇关于确定活动是否由通知调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆