首页 > 系统相关 >Android 11.0 关于app进程保活

Android 11.0 关于app进程保活

时间:2024-07-30 20:08:13浏览次数:13  
标签:task pid app 11.0 保活 boolean ProcessList ADJ

需求:客户某些重要的app,在后台或者在内存紧张的时候,不允许被杀死

ActivityManagerService

./frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

    //清除与该进程的所有连接
    final void handleAppDiedLocked(ProcessRecord app,
            boolean restarting, boolean allowRestart) {
        int pid = app.pid;
        boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1,
                false /*replacingPid*/);
        if (!kept && !restarting) {
            removeLruProcessLocked(app);
            if (pid > 0) {
                ProcessList.remove(pid);
            }
        }

        if (mProfileData.getProfileProc() == app) {
            clearProfilerLocked();
        }

        mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> {
            Slog.w(TAG, "Crash of app " + app.processName
                    + " running instrumentation " + app.getActiveInstrumentation().mClass);
            Bundle info = new Bundle();
            info.putString("shortMsg", "Process crashed.");
            finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
        });
    }


    final boolean cleanUpApplicationRecordLocked(ProcessRecord app,
            boolean restarting, boolean allowRestart, int index, boolean replacingPid) {
        if (index >= 0) {
            removeLruProcessLocked(app);
            ProcessList.remove(app.pid);
        }
        //add text
        boolean app_flag = false;
        if("com.android.xxx".contains(app.processName)){
            app_flag = true;
        }
        //add text
        ...
        if ( !app_flag && (!app.isPersistent() || app.isolated)) {//进行判断
            if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
                    "Removing non-persistent process during cleanup: " + app);
            if (!replacingPid) {
                mProcessList.removeProcessNameLocked(app.processName, app.uid, app);
            }
            mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());//清理某个app进程
        } else if (!app.removed) {
        
        ...

提高某个app的adj,防止系统内存紧张查杀

./frameworks/base/services/core/java/com/android/server/am/OomAdjuster.java

    @GuardedBy("mService")
    private final boolean updateOomAdjLocked(ProcessRecord app, int cachedAdj,
            ProcessRecord TOP_APP, boolean doingAll, long now) {
        if (app.thread == null) {
            return false;
        }

        app.resetCachedInfo();
        UidRecord uidRec = app.uidRecord;
        if (uidRec != null) {
            if (DEBUG_UID_OBSERVERS) {
                Slog.i(TAG_UID_OBSERVERS, "Starting update of " + uidRec);
            }
            uidRec.reset();
        }

        computeOomAdjLocked(app, cachedAdj, TOP_APP, doingAll, now, false, true);

        boolean success = applyOomAdjLocked(app, doingAll, now, SystemClock.elapsedRealtime());
        ...
ADJ级别	 
NATIVE_ADJ	-1000	native进程
SYSTEM_ADJ	-900	仅指system_server进程
PERSISTENT_PROC_ADJ	-800	系统persistent进程
PERSISTENT_SERVICE_ADJ	-700	关联着系统或persistent进程
FOREGROUND_APP_ADJ	0	前台进程
VISIBLE_APP_ADJ	100	可见进程
PERCEPTIBLE_APP_ADJ	200	可感知进程,比如后台音乐播放

解读Android进程优先级ADJ算法

./frameworks/base/services/core/java/com/android/server/am/OomAdjuster.java

    private boolean isInWhitelist(ProcessRecord pr) {
        String packageName = pr.info.packageName;
        List<String> whitelist = new ArrayList();
        if(whitelist != null && whitelist.size() > 0){
            for (String token : whitelist) {
                if (packageName.startsWith(token)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    private final boolean applyOomAdjLocked(ProcessRecord app, boolean doingAll, long now,
            long nowElapsed) {
        boolean success = true;

        if (app.getCurRawAdj() != app.setRawAdj) {
            app.setRawAdj = app.getCurRawAdj();
        }
        ...
        //add text update
        if (app.curAdj != app.setAdj) { //把新的adj更新到lmkd,然后lmkd根据adj等级查杀
            /*ProcessList.setOomAdj(app.pid, app.uid, app.curAdj);
            if (DEBUG_SWITCH || DEBUG_OOM_ADJ || mService.mCurOomAdjUid == app.info.uid) {
                String msg = "Set " + app.pid + " " + app.processName + " adj "
                        + app.curAdj + ": " + app.adjType;
                reportOomAdjMessageLocked(TAG_OOM_ADJ, msg);
            }
            app.setAdj = app.curAdj;
            app.verifiedAdj = ProcessList.INVALID_ADJ;
            synchronized (mCachedAppOptimizer) {
                app.mSetAdjForCompact = app.setAdj;
            }*/

            boolean is_white_apps_flag = false;
            if (isInWhitelist(app) && (app.curAdj > ProcessList.PERSISTENT_SERVICE_ADJ)) {
                is_white_apps_flag = true;
            }
            if (is_white_apps_flag) {
                //是白名单,把adj提升为persistent进程
                ProcessList.setOomAdj(app.pid, app.uid, ProcessList.PERSISTENT_SERVICE_ADJ);
                if (DEBUG_SWITCH || DEBUG_OOM_ADJ || mService.mCurOomAdjUid == app.info.uid) {
                    String msg = "Set " + app.pid + " " + app.processName + " adj "
                            + app.curAdj + ": " + app.adjType;
                    reportOomAdjMessageLocked(TAG_OOM_ADJ, msg);
                }
                app.setAdj = ProcessList.PERSISTENT_SERVICE_ADJ;
                app.verifiedAdj = ProcessList.INVALID_ADJ;
            } else {
                ProcessList.setOomAdj(app.pid, app.uid, app.curAdj);
                if (DEBUG_SWITCH || DEBUG_OOM_ADJ || mService.mCurOomAdjUid == app.info.uid) {
                    String msg = "Set " + app.pid + " " + app.processName + " adj "
                            + app.curAdj + ": " + app.adjType;
                    reportOomAdjMessageLocked(TAG_OOM_ADJ, msg);
                }
                app.setAdj = app.curAdj;
                app.verifiedAdj = ProcessList.INVALID_ADJ;
            }
            synchronized (mCachedAppOptimizer) {
                app.mSetAdjForCompact = app.setAdj;
            }
        }
        //add text update

        final int curSchedGroup = app.getCurrentSchedulingGroup();
        if (app.setSchedGroup != curSchedGroup) {
            int oldSchedGroup = app.setSchedGroup;
            
            ...

点击Recent时,客户主动清理app后台时,拦截

frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java

        boolean removeTaskById(int taskId, boolean killProcess, boolean removeFromRecents,
              String reason) {
          final Task task =
                  mRootWindowContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
          if (task != null) {
            //add text
			ComponentName component = task.getBaseIntent().getComponent();
			if(component!=null){
				String pkg=component.getPackageName();
				List<String> list= new ArrayList();
                list.add("com.android.sss");
				if(list!=null && list.contains(pkg)){
					return false;
				}
			}
           //add text
            removeTask(task, killProcess, removeFromRecents, reason);
            return true;
          }
          Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
          return false;
        }
        
    void removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason) {
        if (task.mInRemoveTask) {
            // Prevent recursion.
            return;
        }
        task.mInRemoveTask = true;
        try {
            task.performClearTask(reason);
            cleanUpRemovedTaskLocked(task, killProcess, removeFromRecents);
            mService.getLockTaskController().clearLockedTask(task);
            mService.getTaskChangeNotificationController().notifyTaskStackChanged();
            if (task.isPersistable) {
                mService.notifyTaskPersisterLocked(null, true);
            }
        } finally {
            task.mInRemoveTask = false;
        }
    }

低内存时,禁止某个app被kill掉功能实现(lowmemorykiller)

+++ b/system/memory/lmkd/lmkd.cpp
@@ -2080,6 +2080,15 @@ static int kill_one_process(struct proc* procp, int min_oom_score, enum kill_rea
    tgid = proc_get_tgid(pid);
    if (tgid >= 0 && tgid != pid) {
        ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
        goto out;
    }

    taskname = proc_get_name(pid, buf, sizeof(buf));
    if (!taskname) {
        goto out;
    }

+    //add text
+    char packageName[25];
+    strncpy(packageName, taskname, sizeof("com.xx.xx"));//复制
+    ALOGE("packageName=%s,taskname=%s,strcmp=%d",packageName,taskname,strcmp(packageName,"com.android.test"));//比较
+    if(!strcmp(packageName,"com.android.test")){
+        return -1000;
+    }
+    //add text
+
     tasksize = proc_get_size(pid);
     if (tasksize <= 0) {
         goto out;

标签:task,pid,app,11.0,保活,boolean,ProcessList,ADJ
From: https://www.cnblogs.com/kato-T/p/18333252

相关文章

  • 计算机毕业设计django/flask+uniapp私人定制商品订单系统hbuiderx微信小程序
    私人订制订单发布与对应商品出售平台方面的任务繁琐,以至于每年都在私人订制订单发布与对应商品出售平台这方面投入较多的精力却效果甚微,私人订制订单发布与对应商品出售平台的目标就是为了能够缓解私人订制订单发布与对应商品出售平台管理面临的压力,让私人订制订单发布与对......
  • Android 11 关于app的权限重置
    Android11Google针对权限系统又加了更多的限制,比如1.权限的单次授权;2.某个app长时间不使用,权限会被自动更新/重置!关于app的权限重置AndroidFramework权限篇四之AppOps机制Settings里面关于app权限重置的switch流程./packages/apps/Settings/src/com/android/settings/......
  • Meta SAM 2:实时分割图片和视频中对象;Apple Intelligence 首个开发者测试版发布丨 RTE
      开发者朋友们大家好: 这里是「RTE开发者日报」,每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享RTE(Real-TimeEngagement)领域内「有话题的新闻」、「有态度的观点」、「有意思的数据」、「有思考的文章」、「有看点的会议」,但内容仅代表编辑的个人观点,......
  • CSAPP(一)
    0x01关于补码iHATE公式对于char类型2Byte,8位,其中有1位视为符号位表示最大值2^72^62^52^42^32^22^12^001111111UMax:-2^7*0+2^6+2^5+2^4+2^3+2^2+2^1+1=127转为16进制表示即:7FTMax:-2^7+2^6+2^5+2^4+2^3+2^2+2......
  • APP逆向 day24unidbg上
    一.前言今天开始讲app逆向最后一个也是最重要的unidbg,这已经是从初级进阶到中级的了,我会讲unidbg,讲三节课,分为上中下来和大家讲(由简单到难逐步),这节课主要是和大家讲unidbg的介绍并且会结合之前讲的简单案例来让大家理解,如果过程中不太记得之前的位置定位,可以去看之前的课程,在......
  • 基于SpringBoot+Vue+uniapp的竞赛报名系统的详细设计和实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • HarmonyOS APP应用开发项目- MCA助手(Day03持续更新中~)
    简言:gitee地址:https://gitee.com/whltaoin_admin/money-controller-app.git端云一体化开发在线文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/agc-harmonyos-clouddev-view-0000001700053733-V5注:此App参照此教程进行二次修改:https://www.bilibi......
  • Django-APP及项目入门
    1.APP定义:Django中功能的细分,每个APP有独立的数据库、表结构、HTML模版、CSS。创建APPpythonmanage.pystartappapp01重要文件介绍views.py:常用文件,urls中的函数常常在此处定义。models.py:常用文件,对数据库进行操作。2.项目入门确保app也注册(settings.py)......
  • UniApp 原生插件接入步骤
    app插件主要分2种:原生语言插件原生语言插件有分为2类:(1)moduleAPI接口插件这种插件是API插件,有同步或异步API(2)UIcomponent组件插件这种插件是UI视图组件,使用到插件里的UI组件的页面要用nvueUTS插件uts集成步骤参考https://www.cnblogs.com/wenrisheng/p/183230......
  • App Inventor 2 低功耗蓝牙 BlueToothLE 拓展中文文档(完整翻译加强版)
    低功耗蓝牙,也称为蓝牙LE或简称BLE,是一种类似于经典蓝牙的新通信协议,不同之处在于它旨在消耗更少的功耗和成本,同时保持同等的功能。因此,低功耗蓝牙是与耗电资源有限的物联网设备进行通信的首选。BluetoothLE扩展需要Android5.0或更高版本。BlueToothLE拓展中文文档入口......