繁体   English   中英

Android-无法通过通知的操作按钮调用服务

[英]Android - Having trouble with calling a service from an action button of a notification

我希望有一个按钮可以将文本从通知复制到剪贴板。 通知是通过Google的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());
}

这是通知操作调用的服务:

public class clipboardService extends IntentService {
public clipboardService() {
    super("clipboardService");
}

@Override
protected void onHandleIntent(Intent intent) { //This intent will have the values of the first intent to fire, instead of the updated one.
    String msg = (String) intent.getExtras().get("tool");
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("2android",msg);
    clipboard.setPrimaryClip(clip);
}

尽管回答您的问题已经很晚了,但是最近我遇到了同样的问题,而Google导致了我这个没有答案的问题。 因此,这是我的理解,如果将来有人对此进行深入研究。

这是因为PendingIntent使用先前的Intent实例中的已缓存的Intent Extras,除非您明确指示不这样做。 有两种方法可以做到...

  1. 在构造PendingIntent时,请使用FLAG_CANCEL_CURRENTFLAG_UPDATE_CURRENT (在您的情况下最好)作为标志。 第一个标志将自动消除先前的PendingIntent并创建一个全新的标志,第二个标志将仅更新PendingIntent的附加功能,并节省创建一个全新的PendingIntent的开销。

     PendingIntent.getService(this, 0, notificationIntent, FLAG_CANCEL_CURRENT | FLAG_UPDATE_CURRENT); 
  2. 每次都将唯一的requestCode传递给PendingIntent构造函数。 这将每次生成唯一的挂起意图,以便您以后可以访问与特定意图相关联的其他功能。 我认为您不需要这样做。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM