Android 点击Notification事件处理

项目中,要实现一个点击Notification跳转到指定页面的功能,但是这个页面是Fragment之一,Fragment又是在viewpager里面,因此不是仅仅打开Activity就可以的,还需要打开activity后设置viewpager.setCurrentItem()。

			Intent intent = new Intent(this, MainActivity.class);
			intent.putExtra("from_mainservice", true);
			PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
			notif.contentIntent = pIntent;

设置了PendingIntent打开MainActivity,并且intent中有boolean字段,但是在MainActivity中,getIntent().getBooleanExtra("from_mainservice",false)获取的值却为false。尝试了onStart(),onResume()的不同位置,都不能得到正确的值。

后来通过查找stack overflow,找到了原因。

点击Notification的时候,MainActivity已经运行,而getIntent()只能获得启动该Activity的Intent,因此获取到的为null。解决方法为在MainActivity中重写onNewIntent(Intent intent)方法,同时声明PedingIntent的时候,添加标记位PendingIntent.FLAG_UPDATE_CURRENT。

			Intent intent = new Intent(this, MainActivity.class);
			intent.putExtra("from_mainservice", true);
			PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			notif.contentIntent = pIntent;

	@Override
	protected void onNewIntent(Intent newIntent) {
		super.onNewIntent(newIntent);
		if(newIntent.getBooleanExtra("from_mainservice", false)) {
			if(mViewPage != null) {
				mViewPage.setCurrentItem(2);
			}
		} 
	}
参考:

http://stackoverflow.com/questions/6352281/getintent-extras-always-null/6357330#6357330




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值