Notification通过Intent传递参数getIntent()为null的问题解决

来源:互联网 发布:淘宝开店证件照要求 编辑:程序博客网 时间:2024/05/01 23:32

想着通过Notification 发送一条通知

点击通知跳转到一个新的activity

在activity中得到Notification的id,从而能够cancel掉Notification。


但是在Notification发送时候,封装好了intent的数据。

当跳转到了 新的activity的时候,getIntent 什么都得不到。百度查询了好久都没有一个正解。


无奈翻墙google继续寻找原因。最后在 http://stackoverflow.com





//关键两点1.//传递数据想要成功,需要设置这里的flag参数intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//2,新Activity中重写onNewIntent方法




新Activvity的代码

@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);Intent intent = this.getIntent();Bundle bundle = intent.getExtras();int tagId = bundle.getInt("tag");NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);Log.e("OtherActivity", "tag = tagId = "+tagId);nm.cancel(tagId);}

@Overrideprotected void onNewIntent(Intent intent) {// TODO Auto-generated method stubsuper.onNewIntent(intent); setIntent(intent);}







//发送广播的代码
private void initNotification() {// 1:获取NotificationManagerNotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);// 2、封装发送的信息Notification mNotification = new Notification();mNotification.icon = R.drawable.qq;mNotification.tickerText = "收到消息时提示内容";mNotification.defaults = Notification.DEFAULT_SOUND;Intent intent = new Intent(this, OtherActivity.class);Bundle bundle = new Bundle();bundle.putInt("tag", 100);intent.putExtras(bundle);//传递数据想要成功,需要设置这里的flag参数intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);mNotification.setLatestEventInfo(this, "contentTitle", "contentText",mPendingIntent);// 3、发送通知nm.notify(100, mNotification);}





原文详解;




0 0
原创粉丝点击