Android 最近任务列表中隐藏视图

用户需求

偶然在酷安收到一个用户提出的需求,于是便有了实现他的思路
用户提问
在这里插入图片描述
在一番百度后,发现常见的解决思路都是在AndroiManifest.xml中对activity进行属性声明,这并不是我想要的
在这里插入图片描述
写死在xml中无法无法实时对属性进行修改,期望以开关的形式去实现这样的需求,于是再一番百度之后,在一篇文章中了解到其实有三种方式可以解决
http://t.csdn.cn/KV3KF

解决方案

一、 android:excludeFromRecents

适合完全不需要在任务列表展示的界面,并且从当前activity跳转的后续activity也不会在后台显示,适合放主页中一劳永逸

 <activity android:name=".MainActivity"
            android:excludeFromRecents="true"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

二、Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS

类似第一种方式

 Intent intent = new Intent(this,SettingsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivity(intent);

三、setExcludeFromRecents()

//隐藏任务列表开关监听事件
        settingsBinding.switchHideBackgroundTask.setOnCheckedChangeListener((view, isChecked) -> {
    
    
            ActivityManager systemService = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.AppTask> appTasks = systemService.getAppTasks();
            int size = appTasks.size();
            if (size > 0) {
    
    
                appTasks.get(0).setExcludeFromRecents(isChecked);//设置activity是否隐藏
                SPUtils.saveObject(getString(R.string.spf_appHideBackgroundTask), isChecked);//将开关信息存储起来
            }
        });

然后在主页设置一个延迟任务,每次重新冷载入APP都会读取配置去设置,就能根据配置去实现APP是否隐藏任务列表视图了。

//设置是否隐藏任务列表视图
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
        executorService.schedule(() -> {
    
    
            boolean b = SPUtils.readBoolean(getString(R.string.spf_appHideBackgroundTask));
            ActivityManager systemService = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.AppTask> appTasks = systemService.getAppTasks();
            int size = appTasks.size();
            if (size > 0) {
    
    
                appTasks.get(0).setExcludeFromRecents(b);
            }
        }, 2, TimeUnit.SECONDS);//两秒后执行该任务

效果

演示效果

猜你喜欢

转载自blog.csdn.net/qq_29687271/article/details/126122532