通知按钮单击 - 方法调用

时间:2014-07-02 18:04:15

标签: android android-notifications android-pendingintent

我创建了一个Notification以显示在状态栏上。

在通知中,我添加了Button,执行了一些操作。

要调用特定方法,请在按钮上单击我使用建议的方法here

代码:

// Building notification - this code is present inside a Service
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

Intent activityIntent = new Intent(this, HomeActivity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setContentTitle(fileName.toString()).setContentText("Subject")
        .setSmallIcon(R.drawable.ic_app_icon).setContentIntent(pendingIntent).setAutoCancel(false);


// code to add button
Intent openListIntent = new Intent();
openListIntent.putExtra("list_intent", true);
PendingIntent listPendingIntent = PendingIntent.getActivity(this, 0, openListIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.ic_open_list, "List", listPendingIntent);

Notification notification = notificationBuilder.build();

// Code in HomeActivity.java to perform operation on button click

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    boolean openListFlag = intent.getBooleanExtra("list_intent", false);
    if (openListFlag) {
        // code to perform operation
    }
}

我的方法是,当点击通知中的按钮时,我已经传递了Extra布尔值,该值设置为 true

但即使只点击通知(而不是单击按钮),仍然会调用onNewIntent()中的操作。 也就是说,openListFlag的值始终设置为 true

我应该如何确保只在点击按钮时执行该操作?

1 个答案:

答案 0 :(得分:1)

只需使用intent action代替extras,如下所示: Determine addAction click for Android notifications

相关问题