项目里使用了第三方的SDK BuzzBox来实现Notification的消息推送功能。消息推送后,点击打开应用跳转到MainActivity,并根据点击对应NotificationMessage,在主界面显示相关的Fragment。因此点击消息时需要设置跳转的Activity并附带参数。
消息推送实例中设置消息推送方法:
notification.setNotificationClickIntentClass(YourMainActivity.class);
Bundle b = new Bundle();
b.putString("param", "value");
notification.setNotificationClickIntentBundle(b));
而我一开始在MainActivity里直接这么接收Bundle:
Bundle b = getIntent().getExtras();
结果一直是个null。
理论上确实把Bundle参数传给了MainActivity,那么为什么收不到呢?其实问题在于Activity中的Bundle没有更新 。因为MainActivity为singleTask模式,保存在栈中,当重新跳转时,显示了原来的MainActivity。而原来就有intent,现在重新传来intent被丢弃了,因此只要处理新来的intent就能取到参数了。方法是重写接收端Activity的onNewIntent()。
在MainAcitity中:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
protected void onResume() {
super.onResume();
Bundle b = getIntent().getExtras();
}
再偷一张图,我觉得看的比较清楚:
所以其实传递过来的是一个Intent实例(包括参数),怎么处理这个实例在onNewIntent()里。而singleTask默认把intent丢弃了,所以要在onNewIntent()里把它捡回来。
参考:
1.http://blog.youkuaiyun.com/dadoneo/article/details/8170124