当我创建一个通过C2DM发送并在我的应用程序中接收的通知时,我希望在intent附加中传递来自C2DM的推送通知的一些数据。当我第一次打开我的通知时,它工作得很好。然后,根据活动的状态,使用onNewIntent或onCreate接收数据。
但是,如果我通过C2DM发送第二个推送通知,新数据会正确接收到它,但是当从intent获取额外的数据时,我仍然会从前一条消息中获取数据。我想要查看的标题和数据在通知中正确显示。所以一定是我的意图出了问题。如果活动正在运行,或者没有运行,就会发生这种情况。
要创建通知,我执行以下操作:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_stat_notify_push, "Message received", System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.defaults |= Notification.DEFAULT_LIGHTS;
Intent intent = new Intent(context, DesktopApp.class);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("msg_id", msg_id);
intent.putExtra("title", title);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, "New message", title + String.valueOf(msg_id), pendingIntent);
notificationManager.notify(0, notification);
然后阅读意图:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myIntent = getIntent(); // this is just for example purpose
int i = myIntent.getIntExtra("msg_id", -1);
if (i != -1) Toast.makeText(this, "Got message! " + String.valueOf(i), Toast.LENGTH_LONG).show();
}
@Override
public void onNewIntent(Intent intent){
super.onNewIntent(intent);
Bundle extras = intent.getExtras();
if (extras != null) {
int i = extras.getInt("msg_id", -1);
if (i != -1) Toast.makeText(this, "Got message! " + String.valueOf(i), Toast.LENGTH_LONG).show();
}
}
有什么建议吗?
发布于 2012-02-09 17:54:24
您需要为PendingIntent
设置一个干净的标志:
PendingIntent pintent =
PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
看一看at this post,它给出了更长的解释。
发布于 2012-02-24 16:18:01
使用这个
PendingIntent pi = PendingIntent.getActivity(context, UNIQUE_ID,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
https://stackoverflow.com/questions/9208547
复制相似问题