putExtra使用待定意图不起作用

Nem*_*min 22 push-notification android-notifications android-notification-bar android-pendingintent

我在GCMIntentservice中编写了一个代码,用于向许多用户发送推送通知.我使用NotificationManager,在单击通知时将调用DescriptionActivity类.我还将event_id格式的GCMIntentService发送到DescriptionActivity

protected void onMessage(Context ctx, Intent intent) {
     message = intent.getStringExtra("message");
     String tempmsg=message;
     if(message.contains("You"))
     {
        String temparray[]=tempmsg.split("=");
        event_id=temparray[1];
     }
    nm= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    intent = new Intent(this, DescriptionActivity.class);
    Log.i("the event id in the service is",event_id+"");
    intent.putExtra("event_id", event_id);
    intent.putExtra("gcmevent",true);
    PendingIntent pi = PendingIntent.getActivity(this,0, intent, 0);
    String title="Event Notifier";
    Notification n = new Notification(R.drawable.defaultimage,message,System.currentTimeMillis());
    n.setLatestEventInfo(this, title, message, pi);
    n.defaults= Notification.DEFAULT_ALL;
    nm.notify(uniqueID,n);
    sendGCMIntent(ctx, message);

}
Run Code Online (Sandbox Code Playgroud)

这里我在上面的方法中得到的event_id是正确的,即我总是得到更新的.但是在下面的代码中(DescriptionActivity.java):

    intent = getIntent();
    final Bundle b = intent.getExtras();
    event_id = Integer.parseInt(b.getString("event_id"));
Run Code Online (Sandbox Code Playgroud)

这里的event_id总是"5".无论我把什么放在GCMIntentService类中,我得到的event_id总是5.有人可以指出问题吗?是因为未决意图?如果是,那我该怎么处理呢?

Jof*_*rey 42

PendingIntent与第一重用Intent你提供的,那是你的问题.

要避免这种情况,请PendingIntent.FLAG_CANCEL_CURRENT在调用时使用该标志PendingIntent.getActivity()以实际获取新标志:

PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想更新附加内容,请使用该标志 PendingIntent.FLAG_UPDATE_CURRENT


san*_*ago 12

正如Joffrey所说,PendingIntent会与您提供的第一个Intent一起重复使用.您可以尝试使用标志PendingIntent.FLAG_UPDATE_CURRENT.

PendingIntent pi = PendingIntent.getActivity(this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)


小智 5

也许您仍在使用旧的意图。尝试这个:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    //try using this intent

    handleIntentExtraFromNotification(intent);
}
Run Code Online (Sandbox Code Playgroud)