解决方法FLAG_UPDATE_CURRENT行为

时间:2014-10-04 07:28:53

标签: android

我已经定义了一个在事件发生时发出通知的服务。我在通知中添加了通知ID作为额外内容,以便当用户通过通知打开应用程序时,我可以检索活动中的ID并取消特定通知。

问题在于,如果抽屉中随时可见多个通知,则所有通知都会以相同的Extra值结束。这是因为FLAG_UPDATE_CURRENT行为。它将使用新的Extra更新任何现有匹配Intent的额外内容。所以现在我无法检索正确的通知ID来取消它。

有没有办法解决此问题,以便之前的Intents保留其Extra值。

根据文件:

public static final int FLAG_UPDATE_CURRENT Added in API level 3 Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

服务onStartCommand():

int notificationId = getId();
Intent contentIntent = new Intent(this,MainActivity.class);
contentIntent.putExtra(MainActivity.KEY_NOTIFICATION_ID, notificationId);
PendingIntent contentPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_OPEN_APP, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(MyApplication.getContext())
    .setContentTitle("title")
    .setContentText("text")
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(contentPendingIntent);    
notificationManager.notify(notificationId,notificationBuilder.build());

在活动的onCreate()中:

Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            int notificationId = bundle.getInt(KEY_NOTIFICATION_ID);
            if(notificationId != 0){
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(notificationId);
            }
        }

1 个答案:

答案 0 :(得分:0)

一种解决方法是为每个PendingIntent提供唯一的请求代码。您可以重复使用通知ID本身。我们也可以为意图设置一个动作,以便活动可以识别意图。所以将代码更改为:

服务onStartCommand():

public static final String ACTION_NOTIFIED = "ACTION_NOTIFIED"; //added
int notificationId = getId();
Intent contentIntent = new Intent(this,MainActivity.class);
contentIntent.putExtra(MainActivity.KEY_NOTIFICATION_ID, notificationId);
contentIntent.setAction(ACTION_NOTIFIED);//added
PendingIntent contentPendingIntent = PendingIntent.getActivity(this, notificationId, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);//changed
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(MyApplication.getContext())
    .setContentTitle("title")
    .setContentText("text")
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(contentPendingIntent);    
notificationManager.notify(notificationId,notificationBuilder.build());

在Activity的onCreate()中:

if(getIntent().getAction().equals(AppService.ACTION_NOTIFIED)){//added
            Bundle bundle = getIntent().getExtras();
            if(bundle != null){
                int notificationId = bundle.getInt(KEY_NOTIFICATION_ID);
                if(notificationId != 0){
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    notificationManager.cancel(notificationId);
                }
            }
        }//added