安卓 通知 启动应用(不重复创建activity)

在安卓通知中,有时候我们需要点击返回到当前的activity中,而不是创建新的。目前网上的各种setflags感觉没什么用。
经过不断尝试,找到三种比较好的实现方式。

  1. 设置当前activity的android:launchMode="singleTask",这样就不会重复创建新的activity

  1. 获取当前包的启动activity,然后在oncreate函数里提前判断是否已经存在。个人不喜欢这种方式,提高了耦合性。
PendingIntent pendingIntent = PendingIntent.getActivity(
                  context,
                   notifyId,
                  msgIntent,
                  PendingIntent.FLAG_UPDATE_CURRENT);
protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       if (!isTaskRoot()) {
           Intent intent = getIntent();
           String action = intent.getAction();
           if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
               finish();
               return;
           }
       }
   }

https://blog.csdn.net/yinyignfenlei/article/details/78666325

  1. 给intent添加category,缺少这句才是setflags成功不了的原因。
Intent launcher = new Intent(Intent.ACTION_MAIN);
//CATEGORY_LAUNCHER有了这个,你的程序就会出现在桌面上
launcher.addCategory(Intent.CATEGORY_LAUNCHER);
//FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 按需启动的关键,如果任务队列中已经存在,则重建程序
launcher.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
launcher.setComponent(new ComponentName(context,类名));
context.startActivity(launcher);```

https://blog.csdn.net/angcyo/article/details/53116553

posted @ 2020-11-14 21:58  雪落安平  阅读(802)  评论(0)    收藏  举报