ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Android应用具有persistent属性时升级清理AMS缓存数据

2019-05-14 19:50:01  阅读:889  来源: 互联网

标签:int app 系统 persistent 缓存数据 应用 action Android 安装


        Android系统中,为了某些目的需要保证应用运行时尽量不被系统kill(特别是处于后台时),所以都会给应用增加persist标签,以避免在系统低内存时被系统kill,也算是系统级的保活方案, 不过要使android:persistent  属性生效, 普通应用是不行的,需要将应用push至系统目录才行。

 <application
        ……………
        android:persistent="true"
        android:icon="@mipmap/ic_launcher"
        ……
>

但是添加了该属性的应用如果需要进行应用自升级(无论是别的应用进行安装升级还是应用自己安装自己进行应用升级),有一些需要特别注意的地方,否则就会导致程序的运行状态错乱。

          一般没有persistent属性的应用在进行应用自升级的时候,系统会保证程序运行的状态是OK的,因为在安装应用(应用自升级)的过程中,系统会KILL此应用的进程,同时清理之前在AMS(ActivityManagerService)中记录的此应用进程中的各种组件(Activity,Service,Receiver,ContentProvider),在下次该新版本的应用重新启动时,系统会重新new一个进程并重新加载各种组件运行,所以不会有问题;

          当应用有persistent属性并且生效时(不但要添加persist标签,还要是系统签名或者有系统权限),系统安装新应用的过程与安装不带此属性的过程不同,初次覆盖系统应用安装时,系统会保护进程或者,安装新版本不会杀掉该进程。原因如下:

private final boolean killPackageProcessesLocked(String packageName, int appId,
            int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
            boolean doit, boolean evenPersistent, String reason) {
        ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
 
        // Remove all processes this package may have touched: all with the
        // same UID (except for the system or root user), and all whose name
        // matches the package name.
        final int NP = mProcessNames.getMap().size();
        for (int ip=0; ip<NP; ip++) {
            SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
            final int NA = apps.size();
            for (int ia=0; ia<NA; ia++) {
                ProcessRecord app = apps.valueAt(ia);
                if (app.persistent && !evenPersistent) {
                    // we don't kill persistent processes
                    continue;(如果有persistent属性而且没有指定要KILL带由此属性的标记的,则跳过)
                }
                if (app.removed) {
                    if (doit) {
                        procs.add(app);
                    }
                    continue;
                }
                // Skip process if it doesn't meet our oom adj requirement.
                if (app.setAdj < minOomAdj) {
                    continue;
                }
                // If no package is specified, we call all processes under the
                // give user id.
                if (packageName == null) {
                    if (app.userId != userId) {
                        continue;
                    }
                    if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) {
                        continue;
                    }
                // Package has been specified, we want to hit all processes
                // that match it.  We need to qualify this by the processes
                // that are running under the specified app and user ID.
                } else {
                    final boolean isDep = app.pkgDeps != null
                            && app.pkgDeps.contains(packageName);
                    if (!isDep && UserHandle.getAppId(app.uid) != appId) {
                        continue;
                    }
                    if (userId != UserHandle.USER_ALL && app.userId != userId) {
                        continue;
                    }
                    if (!app.pkgList.containsKey(packageName) && !isDep) {
                        continue;
                    }
                }
 
                // Process has passed all conditions, kill it!
                if (!doit) {
                    return true;
                }
                app.removed = true;
                procs.add(app);
            }
        }
 
        int N = procs.size();
        for (int i=0; i<N; i++) {
            removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
        }
        updateOomAdjLocked();
        return N > 0;
    }

      系统不会清理之前在AMS(ActivityManagerService)中记录的各种组件的信息,只会把新版应用中的各种组件记录到AMS中。

如果前后两个版本的应用的某个组件如Actvivity名称没有变化,但是内部增加了很多新的类和新的逻辑实现,或者使用了代码加固混淆,就会导致加载的组件有的是新版本的有的是老版本,导致程序功能错乱。一种解决的方法如下:

解决方案:

方案一:

安装完新版本后重启系统(比较暴力),重启系统后,系统将会启动新版本应用,更新后的系统应用会“变成”普通应用,但是同时具备系统权限,以后再进行覆盖安装时,将不再需要重启就可以生效,AMS不会再缓存进程信息。

 

 

方案二:

在应用内执行如下逻辑

在应用内接收新版应用安装完成的广播,当APK发生更新或安装时, 匹配自己的包名,然后调用context的startInstrumentation 方法,该方法会强制系统KILL应用进程并清理AMS对各种组件的状态记忆并重新启动该应用。

1.注册广播接收者

 <receiver
            android:name=".AppStateReceiver"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED"></action>
                <action android:name="android.intent.action.PACKAGE_REPLACED"></action>
                <action android:name="android.intent.action.PACKAGE_REMOVED"></action>
                <data android:scheme="package"/>
            </intent-filter>
        </receiver>

,

public class AppStateReceiver extends BroadcastReceiver {

    private static final String TAG = "AppStateReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        String dataString = intent.getDataString();
        String packagename = "";
        if (!TextUtils.isEmpty(dataString) && dataString.contains(":")){
            String[] split = dataString.split(":");
            if (split.length > 1){
                packagename = split[1];
            }
        }
        Log.d(TAG,"action:" + action + "    dataString:" + dataString);
        if (action.equals("android.intent.action.PACKAGE_ADDED")){
            //app 被安装
            
        }else if (action.equals("android.intent.action.PACKAGE_REPLACED")){
            //应用被更新
             if (context.getPackageName().equals(packagename)){
                     boolean b = context.startInstrumentation(new ComponentName(getApplicationContext(), InstrumentationRoboot.class), null, null);
            }
        }else if (action.equals("android.intent.action.PACKAGE_REMOVED")){
            //应用被卸载
            
        }
    }
}

 

3.InstrumentationRoboot

public class InstrumentationRoboot extends Instrumentation {
    @Override
    public void onCreate(Bundle arguments) {
        super.onCreate(arguments);
        Log.v("test", "Hello from Robot");
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.hello">

    
    <instrumentation
        android:name="com.test.hello.InstrumentationRoboot"
        android:targetPackage="com.test.hello"/>

</manifest>

这样,初次覆盖安装时,就会清理AMS的缓存, 应用安装完成会重启,并打印出  Hello from Robot

 

 

参考:

https://blog.csdn.net/asanwang007/article/details/54178350

https://stackoverflow.com/questions/13803495/instrument-android-app-with-startinstrumentation?answertab=active#tab-top

https://www.jianshu.com/p/62dabd69a409

标签:int,app,系统,persistent,缓存数据,应用,action,Android,安装
来源: https://blog.csdn.net/lindroid/article/details/90213146

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有