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

65 篇文章 0 订阅
55 篇文章 0 订阅

想着通过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的代码

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.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);
		
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		
		 setIntent(intent);
	}







 

//发送广播的代码	
private void initNotification() {
		// 1:获取NotificationManager
		NotificationManager 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);
	}





原文详解;




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百世修行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值