Android:点击状态栏通知的事件

Tim*_*len 13 notifications android

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

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);
}
Run Code Online (Sandbox Code Playgroud)

单击通知时,我想调用一个方法,最好能够访问通知的ID.

提前致谢,

蒂姆

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

McS*_*tch 17

我认为处理通知点击的最佳方式(可能是唯一的方法?)是在PendingIntent调用的类中定义一个方法(在本例中为MainActivity).您可以在将其传递到getActivity()之前修改您的意图以包含通知的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);
Run Code Online (Sandbox Code Playgroud)

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

更新:

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

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

另外,"yourpackage"应替换为包含您的类的包的名称,例如"com.project.foo".