通知的 onClick() 监听器

3

当通知被点击时,我希望能高亮一个ListItem。我的活动已经在显示ListView,所以我不能在点击通知时再次打开它。我已经搜索了很多,但我认为没有任何适用于通知的onClick()方法。那么请告诉我该怎么做?

这是我生成通知的方式

Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(context, notification_id, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setTicker("Smart Locator");
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle(name);
DetailsContainer dc = new LocationDetails(context).getDetails(location);
mBuilder.setContentText(date + ", " + dc.area + " " + dc.locality);
mBuilder.setContentIntent(pIntent).getNotification();
mBuilder.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(document_id, notification_id, mBuilder.build());

我认为点击通知会创建一个Intent,在清单文件中你可以指定哪个activity来处理它。从那里,你需要一些数据来知道你点击的通知类型和你想选择的ListView数据的位置。 - OneCricketeer
可能是重复的问题:如何为通知设置点击监听器? - OneCricketeer
2个回答

3
您可以在待处理意图中添加一个额外的参数。
final Intent intent = new Intent(this, MyActivity.class);
intent.setData(data);
intent.putExtra("key", "clicked");
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent), 0);

然后,当您的活动“重新启动”时,您可以通过接收到的捆绑包检查通知是否被点击。
@Override
protected void onCreate(Bundle savedInstanceState) {
    processIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {     
    processIntent(intent);
};

private void processIntent(Intent intent){
    //get your extras
    //if clicked, do something with ListView
}

点击这个问题获取更多信息。


1
请尝试不要从其他地方复制答案。 - OneCricketeer
我没有抄袭答案,我已经给出了他需要检查通知点击的逻辑,甚至放置了代码的来源。 - John Roberts
当你的声望提高后,你可以将一个问题标记为重复。 - OneCricketeer

1

在您的待定意图中添加一个额外的内容:

final Intent intent = new Intent(this, MyActivity.class);
intent.setData(data);
intent.putExtra("NotClick", true);
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent), 0);

在您的活动中使用以下代码:
@Override
protected void onNewIntent(Intent intent) {
    try {
        //on click notification
        Bundle extras = intent.getExtras();
        if (extras.getBoolean("NotClick")) {
             //Do your stuff here 
        }
    } catch (Exception e) {
        Log.e("onclick", "Exception onclick" + e);
    }
}

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