【问题标题】:Intent Intents.Insert.ACTION only works the first time?Intent Intents.Insert.ACTION 仅在第一次有效?
【发布时间】:2014-05-19 07:30:45
【问题描述】:

我的 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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      系统兑现意图,因此在您的 PendingIntent 中,不要输入 0 作为标志,而是使用 (PendingIntent.FLAG_UPDATE_CURRENT),试试这个:

      PendingIntent.getActivity(context, 0, saveIntent, PendingIntent.FLAG_UPDATE_CURRENT);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多