Intent Intents.Insert.ACTION仅在第一次工作?

问题描述 投票:1回答:2

我的Android服务使用自定义按钮创建通知。自定义按钮的操作应打开“创建联系人”系统屏幕,并预先填写电话号码。这是代码:

// create the base notification
Intent notificationIntent = new Intent(context, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(
    context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
    .setSmallIcon(R.drawable.ic_launcher)
    .setContentTitle(title)
    .setContentText(text)
    .setAutoCancel(false)
    .setOngoing(true)
    .setContentIntent(pendingIntent);

// add the action to save to contacts
Intent saveIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
saveIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
saveIntent.putExtra(ContactsContract.Intents.Insert.PHONE, text);
saveIntent.putExtra(ContactsContract.Intents.Insert.PHONE_TYPE,
    ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
PendingIntent pendingSaveIntent = PendingIntent.getActivity(context, 0, saveIntent, 0);
builder.addAction(0, "Save to Contacts", pendingSaveIntent);

// show the notification
context.getSystemService(Context.NOTIFICATION_SERVICE).notify(0, builder.build());

该代码在第一次运行时效果很好(假设我将“ 01234-1234567”传递给了它)。但是,随后的调用将继续显示第一次显示的对话框,并且对话框中具有相同的值。因此,即使我再次使用输入中的另一个数字(“ Intents.Insert.PHONE”额外值的“ text”值)再次调用该片段代码,也始终会得到“ 01234-1234567”。

我尝试取消“联系人”屏幕,手动创建一个新联系人,完全停止“联系人”应用程序...无论如何,下次我点击通知按钮时,屏幕上将显示我最初在第一个传递的值尝试。

您有任何解释或发现代码中有任何错误吗?

java android android-intent android-contacts android-notifications
2个回答
1
投票

我解决了。基本上,系统会缓存意图,除非它们的区别不仅仅是多余的参数。在我的代码中,我仅更改电话号码,因此它始终使用相同的(第一个)缓存意图。解决方案是使用标志来取消当前缓存的意图并创建一个新的意图。

PendingIntent pendingSaveIntent = PendingIntent.getActivity(
        context, 0, saveIntent, PendingIntent.FLAG_CANCEL_CURRENT);

0
投票

系统兑现意图,因此在(PendingIntent.FLAG_UPDATE_CURRENT)中,不要在您的PendingIntent中输入0作为标志,请尝试以下操作:

© www.soinside.com 2019 - 2024. All rights reserved.