Android-从通知的操作按钮调用服务时遇到问题

Android-从通知的操作按钮调用服务时遇到问题,android,android-notifications,google-cloud-messaging,intentservice,Android,Android Notifications,Google Cloud Messaging,Intentservice,我希望能够有一个按钮,将通知中的文本复制到剪贴板。通知通过谷歌的GCM服务发送 当我第一次按下“复制”按钮时,通知到达,一切正常,文本通过按钮发送意图的服务进入剪贴板。当我按下“复制”按钮时,第二次收到带有不同文本的通知时,第一次通知的内容将进入剪贴板,而不是新通知。当我调试代码时,似乎调用服务的意图具有新内容,但将其放入剪贴板的服务使用旧通知的参数运行,就好像服务的同一会话被旧意图唤醒一样 你知道为什么会这样吗 // Called by the GCM notification handler

我希望能够有一个按钮,将通知中的文本复制到剪贴板。通知通过谷歌的GCM服务发送

当我第一次按下“复制”按钮时,通知到达,一切正常,文本通过按钮发送意图的服务进入剪贴板。当我按下“复制”按钮时,第二次收到带有不同文本的通知时,第一次通知的内容将进入剪贴板,而不是新通知。当我调试代码时,似乎调用服务的意图具有新内容,但将其放入剪贴板的服务使用旧通知的参数运行,就好像服务的同一会话被旧意图唤醒一样

你知道为什么会这样吗

// Called by the GCM notification handler

private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
    Intent notificationIntent = new Intent(this, clipboardService.class);
    notificationIntent.putExtra("tool",msg);
    PendingIntent serviceIntent = PendingIntent.getService(this, 0, notificationIntent, 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_stat_gcm)
                    .setContentTitle("Here's your text!")
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(msg))
                    .setContentText(msg)
                    .addAction(R.drawable.ic_stat_gcm, "Copy", serviceIntent); // <--- The intent will have the right (new) value on the second run
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

虽然现在回答你的问题已经很晚了,但最近我遇到了同样的问题,谷歌给了我这个没有答案的问题。所以我的理解是,如果将来有人把这个挖出来

这是因为
pendingent
使用先前的intent实例中的缓存的intent extra,除非您明确告诉它不要这样做。有两种方法可以做到这一点

  • 在构造
    挂起内容时,使用
    标志\u取消\u当前
    标志\u更新\u当前
    (最适合您的情况)作为标志。第一个标志将自动关闭以前的
    pendingent
    并创建一个全新的标志,第二个标志将仅更新
    pendingent
    的额外内容,并节省创建全新标志的开销

    PendingIntent.getService(this, 0, notificationIntent, 
                             FLAG_CANCEL_CURRENT |  FLAG_UPDATE_CURRENT);
    
  • 每次都将唯一的
    requestCode
    传递给
    pendingent
    构造函数。这将为每次生成唯一的挂起意图,以便您以后可以访问与特定意图关联的额外意图。我相信这在你的情况下是不需要的

    PendingIntent.getService(this, UNIQUE_ID, pi, 0);
    
  • PendingIntent.getService(this, UNIQUE_ID, pi, 0);