Android在任意位置由Notification跳向指定fragment
16lz
2021-01-25
前段时间在项目中遇到的需求,点击通知notification要打开一个fragment页面,并且主Activity的加载模式时singTask,就很头疼。
搞了半天。在这里将解决方案记下来:
NotificationUtil:
NotificationCompat.Builder builder builder = new NotificationCompat.Builder(context);/** *Notification布局设置*///首先,带参跳到主Activity上Intent toFragment= new Intent(context, MainActivity.class);intent.putExtra("toValue", "跳转fragment");PendingIntent pend = PendingIntent.getActivity(context,201,toFragment,PendingIntent.FLAG_UPDATE_CURRENT);builder.setContentIntent(pend);builder.setFullScreenIntent(pend, true);NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);notificationManager.notify(3, builder.build());
主Activity:
@Override protected void onNewIntent(Intent intent) { //点击通知栏到主Activity时 会执行这个方法 getNotify(intent); setIntent(intent); } private void getNotify(Intent intent) { //拿到参数后 首先判断是不是为空 String value = intent.getStringExtra("toValue"); if (!TextUtils.isEmpty(value)) { switch (value) { //在进行判断需要做的操作 case "跳转fragment": //在activity中切换fragment break; } } //做完操作以后必须将toValue的值初始化 intent.putExtra("toValue", ""); super.onNewIntent(intent); }
现在看着也很简单,但是当时遇到问题的时候还不知道Activity有onNewIntent这个方法,所以浪费时间挺长的,算是长知识了。
更多相关文章
- Android(安卓)对话框(Dialog)
- android进程间通信:使用AIDL
- 最近总结的android疑惑(二)
- Android(安卓)Studio - 快捷键详解-MAC版
- Android(安卓)EditText自定义样式的方法
- React Native填坑之旅--与Android模块通信
- 解决Android帧动画在Oncreate中启动只显示第一帧
- Android模拟翻书效果
- Android(安卓)studio2.2 启动模拟器出现“/dev/kvm is not found