安卓:状态栏通知的点击事件

13

我有以下代码来创建状态栏通知:

public void txtNotification(int id, String msg){
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(android.R.drawable.sym_action_email, msg, System.currentTimeMillis());

    // The PendingIntent will launch activity if the user selects this notification
    Intent intent = new Intent(this, MainActivity.class)
    intent.putExtra("yourpackage.notifyId", id);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 0);

    notification.setLatestEventInfo(this, "title", msg, contentIntent);

    manager.notify(id, notification);
}

当通知被点击时,我想调用一个方法,并且最好能够访问通知的id。

提前感谢您的帮助,

Tim

(编辑:阅读了第一个答案后,我更新了我的代码,但是我仍然不知道如何监听意图)


抱歉,我忘了提到我几天前更新了我的答案。如果您还有问题,请告诉我。 - McStretch
啊,谢谢。我在那里读了一些东西,但那大多是关于对象的技术规格。那个页面非常有用。 - Tim van Dalen
2个回答

17

我认为处理通知点击的最佳方式(也许是唯一的方式?)是在调用PendingIntent的类中定义一个方法(在这种情况下是MainActivity)。在传递给getActivity()之前,您可以修改intent以包含通知的id:

// The PendingIntent will launch activity if the user selects this notification
Intent intent = new Intent(this, MainActivity.class)
intent.putExtra("yourpackage.notifyId", id);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 0);

然后在MainActivity中查找此意图,并调用您在类中定义的方法来处理通知。您可以从传入的Intent中提取id。

更新:

为了使您的Activity处理通知,您需要首先在AndroidManifest.xml文件中定义Activity,包括您需要的任何意图过滤器。然后在Activity的onStart()中,您可以从传入的意图中提取额外信息,并根据该数据采取行动。这是一个高级概述,因此建议您阅读开发指南的部分以熟悉相关概念。以下页面是一个很好的起点:

http://developer.android.com/guide/topics/fundamentals.html

同时,“yourpackage”应替换为包含您的类的包的名称,例如“com.project.foo”。


谢谢,我对Android开发还很新,以前从未使用过意图。我该如何设置监听器? - Tim van Dalen
对我来说,没有packagename也可以工作。谢谢! :) - Ravi Dhoriya ツ
1
如果您有许多不同的通知类型,可以通过提供一个意图数组来简化生活,其中第一个意图为空,只收集单击。也就是说,第三个参数应该是Intent[]。 - slott

2
对于像我这样的新手: 在MainActivity中获取yourpackage.notifyId:
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle intent_extras = getIntent().getExtras();
        if (intent_extras != null && intent_extras.containsKey("yourpackage.notifyId"))
        {
          //Do the codes
        }

}

在我的情况下 - 我用它来确定是用户还是由GcmIntentService创建的通知调用打开了我的主活动... 附注:我使用了不带“yourpackage”名称,也可以正常工作。

1
使用没有“yourpackage”前缀的名称可以工作,但要注意这是有风险的,因为其他意图的额外信息可能包含相同的键,这可能会导致错误的行为...所以最好使用包命名空间。 - sjkm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接