使用PendingIntent传递数据

Dea*_*ely 6 notifications android 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());      
}
Run Code Online (Sandbox Code Playgroud)

这是活动的代码段:

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

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

        }
Run Code Online (Sandbox Code Playgroud)

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

x-c*_*ode 14

现有问题涉及此主题

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

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

PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)

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

此示例更改操作:

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

(动作可以是任何东西,只要它与你在其他地方使用相同类的动作不同.)

最新版本的Javadoc中有一个很好的解释,用于待定意图.特别是我引用的这句话:

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