【发布时间】:2012-03-01 18:53:18
【问题描述】:
当我创建一个通过 C2DM 发送并在我的应用程序中接收的通知时,我想在 Intent Extras 中传递 C2DM 推送通知附带的一些数据。这在我第一次打开通知时工作正常。然后根据活动的状态使用 onNewIntent 或 onCreate 接收数据。
但是,如果我通过 C2DM 发送第二个推送通知,它会正确接收到新数据,但是当从意图中获取附加信息时,我仍然会从上一条消息中获取数据。我想查看的标题和数据在通知中正确显示。所以我的意图一定是错误的。如果 Activity 正在运行或未运行,则会发生这种情况。
要创建通知,我执行以下操作:
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();
}
}
有什么建议吗?
【问题讨论】:
-
感谢 onNewIntent() 方法解决了我的问题:)
标签: android android-intent notifications push-notification