Android(安卓)点击Notification事件处理
16lz
2021-01-26
项目中,要实现一个点击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;
@Overrideprotected 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
更多相关文章
- android之自定义组合控件
- android通过MediaProjectionManager录屏关联MediaCodec获取h264
- Android学习笔记(24):进度条组件ProgressBar及其子类
- Android(安卓)Studio中常用设置与快捷键(私人珍藏,Eclipse转AS必看
- HotApp小程序统计开发总结之设置了navigationBarBackgroundColor
- Android使用ethtool工具查询/设置以太网网卡状态
- 手把手教你使用MPAndroidChart实现柱状图,饼状图和线性图
- 【Android】 解析Json 数据示例
- Android(安卓)Studio 安装教程以及gradle配置