繁体   English   中英

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

[英]Android: Click event for Status bar notification

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

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。

提前致谢,

蒂姆

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

我认为处理通知点击的最佳方式(可能是唯一的方法?)是在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);

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

更新:

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

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

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

对于像我这样的假人:在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 ... PS我已经使用了没有“youpackage”的名字,也可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM