使用PendingIntent传递数据

时间:2014-08-07 00:32:57

标签: android notifications android-pendingintent

我正在尝试发出消息已到达的通知。我添加了一个动作,期望在通知上显示一个图标(smallredball)。我希望如果用户点击smallredball,主要活动将启动,并且检查附加组件的活动将看到订单执行与正常启动时不同的操作。

通知显示在目标手机(运行KitKat)和文本上,但小球图标从不显示。当用户触摸通知时,活动无需额外执行。编辑:活动现在正在获得额外的捆绑。

这是发送通知的代码:

private void raiseNotification( String username, String mesText) 
{
    DebugLog.debugLog("GCMIntentService: Attempting to Raise Notification ", false);
    NotificationCompat.Builder b = new NotificationCompat.Builder(this);

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("whattodo", "showmessage");
    intent.setAction(Long.toString(System.currentTimeMillis())); //just to make it unique from the next one
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);


    b.setContentTitle("New SafeTalk Message")
    .setSmallIcon(R.drawable.note24x24)
    .setContentText("From " + username + "  " + mesText)
    .setTicker("New SafeTalk Message")
    .setContentIntent(pIntent)
    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
    .setAutoCancel(true)
    .addAction(R.drawable.smallredball, "Read Now", pIntent);

     NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
     mgr.notify(0, b.build());      
}

这是活动的代码段:

        Bundle extras = getIntent().getExtras();
        if (extras == null)
        {
            GlobalStuff.mpBad.start();
        }
        else
        {
            String myOrders =   extras.getString("whattodo");

        if (myOrders.equals("showmessage"))
            GlobalStuff.mpBeep.start();

        }

为什么通知中没有显示图标?由于我将setAutoCancel设置为true,我预计只需触摸通知就会让它消失。但相反,它运行的应用程序不提供额外的捆绑? 谢谢, 迪安

1 个答案:

答案 0 :(得分:11)

an existing question

中介绍了此主题

由于解决这个问题的点和我遇到过的类似问题,在这个主题中有点散布,这是我的两点备忘单:

第1点:使用以下代码创建待处理的意图。最后一个参数中标志的选择很重要:

PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

第2点:待定意图存储在全局系统表中,并且只有它们创建的意图的某些部分才是"键"的一部分。用于查看此表中的内容。附加项不是键的一部分,因此如果您希望两个意图映射到两个不同的待定意图,请确保它们以其他方式不同,例如具有不同的操作,数据或类型。

此示例更改操作:

Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("whattodo", "showmessage");
// add this:
intent.setAction("showmessage");

(该动作可以是任何内容,只要它与您在其他地方使用相同类的内容不同。 )

latest version of the Javadoc for pending intents.中有一个很好的解释,尤其是我引用的这句话:

  

...为了检索PendingIntent,知道两个Intent何时被认为是相同的是很重要的。人们常犯的一个错误就是使用Intent创建多个PendingIntent对象,这些Intent只在其" extra"内容,期望每次获得不同的PendingIntent。这不会发生。用于匹配的Intent部分与Intent.filterEquals定义的部分相同。