【我的Android开发】AMS中Activity栈管理

news2024/11/25 21:26:56

概述

Activity栈管理是AMS的另一个重要功能,栈管理又和Activity的启动模式和startActivity时所设置的Flag息息相关,Activity栈管理的主要处理逻辑是在ActivityStarter#startActivityUnchecked方法中,本文也会围绕着这个方法进进出出,反复摩擦,直到脑海中都是它的形状。goolge的工程师起名还是很讲究的,为什么要带Unchecked呢? Unchecked-不确定,是因为在执行这个方法时,我要启动哪个Activity还没决定呢,具体为什么,我想看过这篇文章你就明白了。

Activity栈管理相关类

ActivityStackSupervisor

Activity栈的管理人

ActivityDisplay

表示一个屏幕,Android支持三种屏幕,主屏幕,外接屏幕,虚拟屏幕(投屏)【这个介绍是从其他地方看来的,并不确定】。一般在手机上只有主屏幕,此时ActivityStackSupervisor与ActivityDisplay都是系统唯一的

TaskRecord

是ActivityTask的记录,TaskRecord是Activity栈的重要管理单元。形象一点理解,记得启动模式的 singleTask 吧?意思就是让这个Activity在单独的TaskRecord中启动。“Task":任务。

ActivityRecord

记录着每个Activity的信息,ActivityRecord和Activity一一对应。

ActivityStack

是ActivityRecord和TaskRecord两者的统一上司,记录着ActivityRecord和TaskRecord的状态。

如果在只有主屏幕的设备上,他们之间的关系大概是这样子的:

请添加图片描述

可以理解为一个屏幕上,可能会有很多个APP进程,每个APP进程对应一个ActivityStack,也就是activity栈,其中由于Activity的启动模式不同,又形成了若干个TaskRecord,其中包含着若干个ActivityRecord。

Activity 的四种启动模式,以及启动标识符

Standard

标准启动模式,启动Activity的时候向发起人的Task顶直接添加即可,返回时依次退出。

SingleTop

栈顶唯一,如果栈顶Activity不是要启动的Activity,则会创建一个新的Activity实例,但如果栈顶Activity就是我们要启动的Activity,就只会调用onNewIntent,而不去再重新创建一个实例。相比Standard,Standard不论如何,都会创建一个新的实例。

SingleTask

栈内唯一。如果发起启动的ActivityRecord所在的TaskRecord中,有要启动的Activity对应的ActivityRecord,则首先将TaskRecord中,目标Activity之上的所有ActivityRecord全都弹出,然后将所在TaskRecord变为ActivityStack的栈顶。

如果发起启动的ActivityRecord所在的TaskRecord中,没有要启动的Activity对应的ActivityRecord,则会在栈顶新建一个TaskRecord,并向其中实例化一个需要启动的Activity对应的ActivityRecord。

SingleInstance

独占一个TaskRecord。启动时,在ActivityStack中查找是否有相同的Activity,如果有,则用这个独占TaskRecord的ActivityRecord对应的Activity。否则新建一个TaskRecord,里面只有它存在。由singleInstance发起的启动,不论是谁,都会在另一个task中启动。

代码实现

通过对"android.app.ActivityThread"进行反射。获取android系统的activity栈

遍历activity栈能够得到当前应用中的全部存活的activity。

        Log.e("Baseactivty", this.getClass().getName() +":oncreate");
        Class activityThreadClass = null;
 
        try {
            activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            int i = 0;
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field activityField = activityRecordClass.getDeclaredField("activity");
                activityField.setAccessible(true);
                Activity activity = (Activity) activityField.get(activityRecord);
 
                Log.e("activityThreadClass", "index:" + i + ",sum:" + activities.size()+ ", class name:" + activity.getClass().getName());
                i++;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

当你在Activity的oncreate中调用上述方法时。你会发现activity列表activities中没有当前的activity,这是由于当前activity还没有被增加栈中。可是onResume中调用上面的函数。就发现当前activity已经被增加栈中。

2.2 重写Instrumentation

监听activity的声明周期。现实自己想要的操作。

首先"绕庄"操作,即在当前project的src文件夹以下新建anroid.app包,然后声明ActivityThread、Instrumentation、LoadedApk三个文件。

ActivityThread类

package android.app;
 
import android.content.pm.ApplicationInfo;
 
public final class ActivityThread {
 
    /**
     * NOTICE: 必须在UI线程调用本方法,否则返回NULL
     *
     * @return
     */
    public static ActivityThread currentActivityThread() {
        return null;
    }
 
    public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
        return null;
    }
}

Instrumentation类

package android.app;
 
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
 
public class Instrumentation {
 
    public void onCreate(Bundle arguments) {
 
    }
 
    public void start() {
 
    }
 
    public void onStart() {
 
    }
 
    public boolean onException(Object obj, Throwable e) {
 
        return false;
    }
 
    public void sendStatus(int resultCode, Bundle results) {
 
    }
 
    public void finish(int resultCode, Bundle results) {
 
    }
 
    public void setAutomaticPerformanceSnapshots() {
 
    }
 
    public void startPerformanceSnapshot() {
 
    }
 
    public void endPerformanceSnapshot() {
 
    }
 
    public void onDestroy() {
 
    }
 
    public Context getContext() {
        return null;
    }
 
    public ComponentName getComponentName() {
        return null;
    }
 
    public Context getTargetContext() {
        return null;
    }
 
    public boolean isProfiling() {
        return false;
    }
 
    public void startProfiling() {
 
    }
 
    public void stopProfiling() {
 
    }
 
    public void setInTouchMode(boolean inTouch) {
 
    }
 
    public void waitForIdle(Runnable recipient) {
 
    }
 
    public void waitForIdleSync() {
 
    }
 
    public void runOnMainSync(Runnable runner) {
 
    }
 
    public Activity startActivitySync(Intent intent) {
 
        return null;
    }
 
    public void addMonitor(ActivityMonitor monitor) {
 
    }
 
    public Instrumentation.ActivityMonitor addMonitor(IntentFilter filter, ActivityResult result, boolean block) {
        return null;
    }
 
    public ActivityMonitor addMonitor(String cls, ActivityResult result, boolean block) {
        return null;
    }
 
    public boolean checkMonitorHit(ActivityMonitor monitor, int minHits) {
        return false;
    }
 
    public Activity waitForMonitor(ActivityMonitor monitor) {
        return null;
    }
 
    public Activity waitForMonitorWithTimeout(ActivityMonitor monitor, long timeOut) {
        return null;
    }
 
    public void removeMonitor(ActivityMonitor monitor) {
 
    }
 
    public boolean invokeMenuActionSync(Activity targetActivity, int requestCode, int flag) {
        return false;
    }
 
    public boolean invokeContextMenuAction(Activity targetActivity, int requestCode, int flag) {
        return false;
    }
 
    public void sendStringSync(String text) {
 
    }
 
    public void sendKeySync(KeyEvent event) {
 
    }
 
    public void sendKeyDownUpSync(int key) {
 
    }
 
    public void sendCharacterSync(int keyCode) {
 
    }
 
    public void sendPointerSync(MotionEvent event) {
 
    }
 
    public void sendTrackballEventSync(MotionEvent event) {
 
    }
 
    public Application newApplication(ClassLoader cl, String className, Context who) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return null;
    }
 
    public void callApplicationOnCreate(Application app) {
 
    }
 
    public Activity newActivity(Class<?> clazz, Context who, IBinder token, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id, Object lastNonConfigurationInstance) throws InstantiationException, IllegalAccessException {
        return null;
    }
 
    public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return null;
    }
 
    public void callActivityOnCreate(Activity target, Bundle icicle) {
 
    }
 
    public void callActivityOnDestroy(Activity target) {
 
    }
 
    public void callActivityOnRestoreInstanceState(Activity target, Bundle savedInstanceState) {
 
    }
 
    public void callActivityOnPostCreate(Activity target, Bundle icicle) {
 
    }
 
    public void callActivityOnNewIntent(Activity target, Intent intent) {
 
    }
 
    public void callActivityOnStart(Activity target) {
 
    }
 
    public void callActivityOnRestart(Activity target) {
 
    }
 
    public void callActivityOnResume(Activity target) {
 
    }
 
    public void callActivityOnStop(Activity target) {
    }
 
    public void callActivityOnSaveInstanceState(Activity target, Bundle outState) {
    }
 
    public void callActivityOnPause(Activity target) {
 
    }
 
    public void callActivityOnUserLeaving(Activity target) {
 
    }
 
    public void startAllocCounting() {
    }
 
    public void stopAllocCounting() {
    }
 
    public Bundle getAllocCounts() {
        return null;
    }
 
    public Bundle getBinderCounts() {
        return null;
    }
 
    public UiAutomation getUiAutomation() {
        return null;
    }
 
    public ActivityResult execStartActivity(final Context who, final IBinder contextThread, final IBinder token, final Activity target, final Intent intent, final int requestCode) {
        return null;
    }
 
    public ActivityResult execStartActivity(final Context who, final IBinder contextThread, final IBinder token, final Activity target, final Intent intent, final int requestCode, final Bundle options) {
        return null;
    }
 
    public ActivityResult execStartActivity(final Context who, final IBinder contextThread, final IBinder token, final Fragment fragment, final Intent intent, final int requestCode) {
        return null;
    }
 
    public ActivityResult execStartActivity(final Context who, final IBinder contextThread, final IBinder token, final Fragment fragment, final Intent intent, final int requestCode, final Bundle options) {
        return null;
    }
 
    protected static final class ActivityMonitor {
    }
 
    public static final class ActivityResult {
    }
 
}

LoadedApk类

package android.app;
 
public class LoadedApk {
    public Application makeApplication(boolean forceDefaultAppClass,
                                       Instrumentation instrumentation) {
        return null;
    }
 
    public ClassLoader getClassLoader() {
        return null;
    }
}

首先"绕庄"的目的是为绕过编译过程,Instrumentation属于内核实现类型,不能直接使用,否则会编译出错。

以下是一个反射的工具类,有lody大神设计

NULL类

/**
 * 用来表示null的类.
 *
 
 */
public class NULL {
}

Reflect类

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
 
import android.annotation.SuppressLint;
 
/**
 * 一个拥有流畅特性(Fluent-API)的反射工具类,
 * 使用起来就像直接调用一样流畅易懂.
 *
 */
@SuppressLint("DefaultLocale")
public class Reflect {
 
    private final Object object;
    private final boolean isClass;
 
    private Reflect(Class<?
 
> type) {
        this.object = type;
        this.isClass = true;
    }
 
    private Reflect(Object object) {
        this.object = object;
        this.isClass = false;
    }
 
    /**
     * 依据指定的类名构建反射工具类
     *
     * @param name 类的全名
     * @return 反射工具类
     * @throws 假设反射出现意外
     * @see #on(Class)
     */
    public static Reflect on(String name) throws ReflectException {
        return on(forName(name));
    }
 
    /**
     * 从指定的类载入起寻找类,并构建反射工具类
     *
     * @param name        类的全名
     * @param classLoader 须要构建工具类的类的类载入器
     *                    loaded.
     * @return 反射工具类
     * @throws ReflectException 假设反射出现意外
     * @see #on(Class)
     */
    public static Reflect on(String name, ClassLoader classLoader) throws ReflectException {
        return on(forName(name, classLoader));
    }
 
    /**
     * 依据指定的类构建反射工具类
     * <p>
     * 当你须要訪问静态字段的时候本方法适合你,
     * 你还能够通过调用 {@link #create(Object...)} 创建一个对象.
     *
     * @param clazz 须要构建反射工具类的类
     * @return 反射工具类
     */
    public static Reflect on(Class<?> clazz) {
        return new Reflect(clazz);
    }
 
    // ---------------------------------------------------------------------
    // 构造器
    // ---------------------------------------------------------------------
 
    /**
     * Wrap an object.
     * <p>
     * Use this when you want to access instance fields and methods on any
     * {@link Object}
     *
     * @param object The object to be wrapped
     * @return A wrapped object, to be used for further reflection.
     */
    public static Reflect on(Object object) {
        return new Reflect(object);
    }
 
    /**
     * 让一个{@link AccessibleObject}可訪问.
     *
     * @param accessible
     * @param <T>
     * @return
     */
    public static <T extends AccessibleObject> T accessible(T accessible) {
        if (accessible == null) {
            return null;
        }
 
        if (accessible instanceof Member) {
            Member member = (Member) accessible;
 
            if (Modifier.isPublic(member.getModifiers()) &&
                    Modifier.isPublic(member.getDeclaringClass().getModifiers())) {
 
                return accessible;
            }
        }
        if (!accessible.isAccessible()) {
            accessible.setAccessible(true);
        }
 
        return accessible;
    }
 
    // ---------------------------------------------------------------------
    // Fluent Reflection API
    // ---------------------------------------------------------------------
 
    /**
     * 将给定字符串的开头改为小写.
     *
     * @param string
     * @return
     */
    @SuppressLint("DefaultLocale")
    private static String property(String string) {
        int length = string.length();
 
        if (length == 0) {
            return "";
        } else if (length == 1) {
            return string.toLowerCase();
        } else {
            return string.substring(0, 1).toLowerCase() + string.substring(1);
        }
    }
 
    private static Reflect on(Constructor<?
 
> constructor, Object... args) throws ReflectException {
        try {
            return on(accessible(constructor).newInstance(args));
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }
 
    private static Reflect on(Method method, Object object, Object... args) throws
            ReflectException {
        try {
            accessible(method);
 
            if (method.getReturnType() == void.class) {
                method.invoke(object, args);
                return on(object);
            } else {
                return on(method.invoke(object, args));
            }
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }
 
    /**
     * 取得内部维护的对象.
     */
    private static Object unwrap(Object object) {
        if (object instanceof Reflect) {
            return ((Reflect) object).get();
        }
 
        return object;
    }
 
    /**
     * 将Object数组转换为其类型的数组.
     * 假设对象中包括null,我们用NULL.class取代.
     *
     * @see Object#getClass()
     */
    private static Class<?
 
>[] types(Object... values) {
        if (values == null) {
            return new Class[0];
        }
 
        Class<?>[] result = new Class[values.length];
 
        for (int i = 0; i < values.length; i++) {
            Object value = values[i];
            result[i] = value == null ?
 
NULL.class : value.getClass();
        }
 
        return result;
    }
 
    /**
     * 取得一个类,此操作会初始化类的static区域.
     *
     * @see Class#forName(String)
     */
    private static Class<?
 
> forName(String name) throws ReflectException {
        try {
            return Class.forName(name);
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }
 
    private static Class<?
 
> forName(String name, ClassLoader classLoader) throws ReflectException {
        try {
            return Class.forName(name, true, classLoader);
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }
 
    /**
     * 假设给定的Class是原始类型,那么将其包装为对象类型,
     * 否则返回本身.
     */
    public static Class<?
 
> wrapper(Class<?> type) {
        if (type == null) {
            return null;
        } else if (type.isPrimitive()) {
            if (boolean.class == type) {
                return Boolean.class;
            } else if (int.class == type) {
                return Integer.class;
            } else if (long.class == type) {
                return Long.class;
            } else if (short.class == type) {
                return Short.class;
            } else if (byte.class == type) {
                return Byte.class;
            } else if (double.class == type) {
                return Double.class;
            } else if (float.class == type) {
                return Float.class;
            } else if (char.class == type) {
                return Character.class;
            } else if (void.class == type) {
                return Void.class;
            }
        }
 
        return type;
    }
 
    /**
     * 取得内部维护的实际对象
     *
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T get() {
        return (T) object;
    }
 
    /**
     * 设置指定字段为指定值
     *
     * @param name
     * @param value
     * @return
     * @throws ReflectException
     */
    public Reflect set(String name, Object value) throws
            ReflectException {
        try {
            Field field = field0(name);
            field.setAccessible(true);
            field.set(object, unwrap(value));
            return this;
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }
 
    /**
     * @param name
     * @param <T>
     * @return
     * @throws ReflectException
     */
    public <T> T get(String name) throws ReflectException {
        return field(name).get();
    }
 
    /**
     * 取得指定名称的字段
     *
     * @param name
     * @return
     * @throws ReflectException
     */
    public Reflect field(String name) throws ReflectException {
        try {
            Field field = field0(name);
            return on(field.get(object));
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }
 
    private Field field0(String name) throws ReflectException {
        Class<?> type = type();
 
        // 先尝试取得公有字段
        try {
            return type.getField(name);
        }
 
        //此时尝试非公有字段
        catch (NoSuchFieldException e) {
            do {
                try {
                    return accessible(type.getDeclaredField(name));
                } catch (NoSuchFieldException ignore) {
                }
 
                type = type.getSuperclass();
            }
            while (type != null);
 
            throw new ReflectException(e);
        }
    }
 
    /**
     * 取得一个Map,map中的key为字段名,value为字段相应的反射工具类
     *
     * @return
     */
    public Map<String, Reflect> fields() {
        Map<String, Reflect> result = new LinkedHashMap<String, Reflect>();
        Class<?> type = type();
 
        do {
            for (Field field : type.getDeclaredFields()) {
                if (!isClass ^ Modifier.isStatic(field.getModifiers())) {
                    String name = field.getName();
 
                    if (!result.containsKey(name))
                        result.put(name, field(name));
                }
            }
 
            type = type.getSuperclass();
        }
        while (type != null);
 
        return result;
    }
 
    /**
     * 调用指定的无參数方法
     *
     * @param name
     * @return
     * @throws androidx.pluginmgr.reflect.ReflectException
     */
    public Reflect call(String name) throws ReflectException {
        return call(name, new Object[0]);
    }
 
    /**
     * 调用方法依据传入的參数
     *
     * @param name
     * @param args
     * @return
     * @throws androidx.pluginmgr.reflect.ReflectException
     */
    public Reflect call(String name, Object... args) throws ReflectException {
        Class<?
 
>[] types = types(args);
 
        try {
            Method method = exactMethod(name, types);
            return on(method, object, args);
        } catch (NoSuchMethodException e) {
            try {
                Method method = similarMethod(name, types);
                return on(method, object, args);
            } catch (NoSuchMethodException e1) {
                throw new ReflectException(e1);
            }
        }
    }
 
    private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException {
        Class<?> type = type();
 
        try {
            return type.getMethod(name, types);
        } catch (NoSuchMethodException e) {
            do {
                try {
                    return type.getDeclaredMethod(name, types);
                } catch (NoSuchMethodException ignore) {
                }
 
                type = type.getSuperclass();
            }
            while (type != null);
 
            throw new NoSuchMethodException();
        }
    }
 
    /**
     * 依据參数和名称匹配方法,假设找不到方法,
     */
    private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException {
        Class<?> type = type();
 
        for (Method method : type.getMethods()) {
            if (isSimilarSignature(method, name, types)) {
                return method;
            }
        }
 
        do {
            for (Method method : type.getDeclaredMethods()) {
                if (isSimilarSignature(method, name, types)) {
                    return method;
                }
            }
 
            type = type.getSuperclass();
        }
        while (type != null);
 
        throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found on type " + type() + ".");
    }
 
    private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?
 
>[] desiredParamTypes) {
        return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes);
    }
 
    /**
     * 创建一个实例通过默认构造器
     *
     * @return
     * @throws androidx.pluginmgr.reflect.ReflectException
     */
    public Reflect create() throws ReflectException {
        return create(new Object[0]);
    }
 
    /**
     * 创建一个实例依据传入的參数
     *
     * @param args
     * @return
     * @throws ReflectException
     */
    public Reflect create(Object... args) throws ReflectException {
        Class<?>[] types = types(args);
 
        try {
            Constructor<?> constructor = type().getDeclaredConstructor(types);
            return on(constructor, args);
        } catch (NoSuchMethodException e) {
            for (Constructor<?> constructor : type().getDeclaredConstructors()) {
                if (match(constructor.getParameterTypes(), types)) {
                    return on(constructor, args);
                }
            }
 
            throw new ReflectException(e);
        }
    }
 
    /**
     * 创建一个动态代理依据传入的类型.
     * 假设我们正在维护的是一个Map,那么当调用出现异常时我们将从Map中取值.
     *
     * @param proxyType 须要动态代理的类型
     * @return 动态代理生成的对象
     */
    @SuppressWarnings("unchecked")
    public <P> P as(Class<P> proxyType) {
        final boolean isMap = (object instanceof Map);
        final InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String name = method.getName();
                try {
                    return on(object).call(name, args).get();
                } catch (ReflectException e) {
                    if (isMap) {
                        Map<String, Object> map = (Map<String, Object>) object;
                        int length = (args == null ?
 
0 : args.length);
 
                        if (length == 0 && name.startsWith("get")) {
                            return map.get(property(name.substring(3)));
                        } else if (length == 0 && name.startsWith("is")) {
                            return map.get(property(name.substring(2)));
                        } else if (length == 1 && name.startsWith("set")) {
                            map.put(property(name.substring(3)), args[0]);
                            return null;
                        }
                    }
 
                    throw e;
                }
            }
        };
 
        return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[]{proxyType}, handler);
    }
 
    /**
     * 检查两个数组的类型是否匹配,假设数组中包括原始类型,将它们转换为相应的包装类型.
     */
    private boolean match(Class<?
 
>[] declaredTypes, Class<?>[] actualTypes) {
        if (declaredTypes.length == actualTypes.length) {
            for (int i = 0; i < actualTypes.length; i++) {
                if (actualTypes[i] == NULL.class)
                    continue;
 
                if (wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i])))
                    continue;
 
                return false;
            }
 
            return true;
        } else {
            return false;
        }
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        return object.hashCode();
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Reflect) {
            return object.equals(((Reflect) obj).get());
        }
 
        return false;
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return object.toString();
    }
 
    /**
     * 取得我们正在反射的对象的类型.
     *
     * @see Object#getClass()
     */
    public Class<?> type() {
        if (isClass) {
            return (Class<?>) object;
        } else {
            return object.getClass();
        }
    }
 
}

ReflectException

/**
 *
 */
public class ReflectException extends RuntimeException {
 
    private static final long serialVersionUID = 663038727503637969L;
 
    public ReflectException(String message) {
        super(message);
    }
 
    public ReflectException(String message, Throwable cause) {
        super(message, cause);
    }
 
    public ReflectException() {
        super();
    }
 
    public ReflectException(Throwable cause) {
        super(cause);
    }
}

接下来是activityThread的代理类

import Reflect;
 
import android.app.ActivityThread;
import android.app.Application;
import android.app.Instrumentation;
 
public class DelegateActivityThread {
 
    private static DelegateActivityThread SINGLETOPN = new DelegateActivityThread();
 
    private Reflect mActivityThreadReflect;
 
    public DelegateActivityThread() {
        mActivityThreadReflect = Reflect.on(ActivityThread.currentActivityThread());
    }
 
    public static DelegateActivityThread getSingletion() {
        return SINGLETOPN;
    }
 
    public Application getInitialApplication() {
        return mActivityThreadReflect.get("mInitialApplication");
    }
 
    public Instrumentation getInstrumentation() {
        return mActivityThreadReflect.get("mInstrumentation");
    }
 
    public void setInstrumentation(Instrumentation newInstrumentation) {
        mActivityThreadReflect.set("mInstrumentation", newInstrumentation);
    }
}

要在Instrumentation进行咱们自己操作的继承类DelegateInstrumentation

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Fragment;
import android.app.Instrumentation;
import android.app.UiAutomation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
 
public class DelegateInstrumentation extends Instrumentation {
 
    private Instrumentation mBase;
 
    /**
     * @param mBase 真正的Instrumentation
     */
    public DelegateInstrumentation(Instrumentation mBase) {
        this.mBase = mBase;
    }
 
    @Override
    public void onCreate(Bundle arguments) {
        mBase.onCreate(arguments);
    }
 
    @Override
    public void start() {
        mBase.start();
    }
 
    @Override
    public void onStart() {
        mBase.onStart();
    }
 
    @Override
    public boolean onException(Object obj, Throwable e) {
        return mBase.onException(obj, e);
    }
 
    @Override
    public void sendStatus(int resultCode, Bundle results) {
        mBase.sendStatus(resultCode, results);
    }
 
    @Override
    public void finish(int resultCode, Bundle results) {
        mBase.finish(resultCode, results);
    }
 
    @Override
    public void setAutomaticPerformanceSnapshots() {
        mBase.setAutomaticPerformanceSnapshots();
    }
 
    @Override
    public void startPerformanceSnapshot() {
        mBase.startPerformanceSnapshot();
    }
 
    @Override
    public void endPerformanceSnapshot() {
        mBase.endPerformanceSnapshot();
    }
 
    @Override
    public void onDestroy() {
        mBase.onDestroy();
    }
 
    @Override
    public Context getContext() {
        return mBase.getContext();
    }
 
    @Override
    public ComponentName getComponentName() {
        return mBase.getComponentName();
    }
 
    @Override
    public Context getTargetContext() {
        return mBase.getTargetContext();
    }
 
    @Override
    public boolean isProfiling() {
        return mBase.isProfiling();
    }
 
    @Override
    public void startProfiling() {
        mBase.startProfiling();
    }
 
    @Override
    public void stopProfiling() {
        mBase.stopProfiling();
    }
 
    @Override
    public void setInTouchMode(boolean inTouch) {
        mBase.setInTouchMode(inTouch);
    }
 
    @Override
    public void waitForIdle(Runnable recipient) {
        mBase.waitForIdle(recipient);
    }
 
    @Override
    public void waitForIdleSync() {
        mBase.waitForIdleSync();
    }
 
    @Override
    public void runOnMainSync(Runnable runner) {
        mBase.runOnMainSync(runner);
    }
 
    @Override
    public Activity startActivitySync(Intent intent) {
        return mBase.startActivitySync(intent);
    }
 
    @Override
    public void addMonitor(ActivityMonitor monitor) {
        mBase.addMonitor(monitor);
    }
 
    @Override
    public ActivityMonitor addMonitor(IntentFilter filter, ActivityResult result, boolean block) {
        return mBase.addMonitor(filter, result, block);
    }
 
    @Override
    public ActivityMonitor addMonitor(String cls, ActivityResult result, boolean block) {
        return mBase.addMonitor(cls, result, block);
    }
 
    @Override
    public boolean checkMonitorHit(ActivityMonitor monitor, int minHits) {
        return mBase.checkMonitorHit(monitor, minHits);
    }
 
    @Override
    public Activity waitForMonitor(ActivityMonitor monitor) {
        return mBase.waitForMonitor(monitor);
    }
 
    @Override
    public Activity waitForMonitorWithTimeout(ActivityMonitor monitor, long timeOut) {
        return mBase.waitForMonitorWithTimeout(monitor, timeOut);
    }
 
    @Override
    public void removeMonitor(ActivityMonitor monitor) {
        mBase.removeMonitor(monitor);
    }
 
    @Override
    public boolean invokeMenuActionSync(Activity targetActivity, int id, int flag) {
        return mBase.invokeMenuActionSync(targetActivity, id, flag);
    }
 
    @Override
    public boolean invokeContextMenuAction(Activity targetActivity, int id, int flag) {
        return mBase.invokeContextMenuAction(targetActivity, id, flag);
    }
 
    @Override
    public void sendStringSync(String text) {
        mBase.sendStringSync(text);
    }
 
    @Override
    public void sendKeySync(KeyEvent event) {
        mBase.sendKeySync(event);
    }
 
    @Override
    public void sendKeyDownUpSync(int key) {
        mBase.sendKeyDownUpSync(key);
    }
 
    @Override
    public void sendCharacterSync(int keyCode) {
        mBase.sendCharacterSync(keyCode);
    }
 
    @Override
    public void sendPointerSync(MotionEvent event) {
        mBase.sendPointerSync(event);
    }
 
    @Override
    public void sendTrackballEventSync(MotionEvent event) {
        mBase.sendTrackballEventSync(event);
    }
 
    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return mBase.newApplication(cl, className, context);
    }
 
    @Override
    public void callApplicationOnCreate(Application app) {
        mBase.callApplicationOnCreate(app);
    }
 
    @Override
    public Activity newActivity(Class<?
 
> clazz, Context context, IBinder token, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id, Object lastNonConfigurationInstance) throws InstantiationException, IllegalAccessException {
        return mBase.newActivity(clazz, context, token, application, intent, info, title, parent, id, lastNonConfigurationInstance);
    }
 
    @Override
    public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return mBase.newActivity(cl, className, intent);
    }
 
    @Override
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        mBase.callActivityOnCreate(activity, icicle);
    }
 
    @Override
    public void callActivityOnDestroy(Activity activity) {
        mBase.callActivityOnDestroy(activity);
    }
 
    @Override
    public void callActivityOnRestoreInstanceState(Activity activity, Bundle savedInstanceState) {
        mBase.callActivityOnRestoreInstanceState(activity, savedInstanceState);
    }
 
    @Override
    public void callActivityOnPostCreate(Activity activity, Bundle icicle) {
        mBase.callActivityOnPostCreate(activity, icicle);
    }
 
    @Override
    public void callActivityOnNewIntent(Activity activity, Intent intent) {
        mBase.callActivityOnNewIntent(activity, intent);
    }
 
    @Override
    public void callActivityOnStart(Activity activity) {
        mBase.callActivityOnStart(activity);
    }
 
    @Override
    public void callActivityOnRestart(Activity activity) {
        mBase.callActivityOnRestart(activity);
    }
 
    @Override
    public void callActivityOnResume(Activity activity) {
        mBase.callActivityOnResume(activity);
    }
 
    @Override
    public void callActivityOnStop(Activity activity) {
        mBase.callActivityOnStop(activity);
    }
 
    @Override
    public void callActivityOnSaveInstanceState(Activity activity, Bundle outState) {
        mBase.callActivityOnSaveInstanceState(activity, outState);
    }
 
    @Override
    public void callActivityOnPause(Activity activity) {
        mBase.callActivityOnPause(activity);
    }
 
    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    @Override
    public void callActivityOnUserLeaving(Activity activity) {
        mBase.callActivityOnUserLeaving(activity);
    }
 
    @Override
    public void startAllocCounting() {
        mBase.startAllocCounting();
    }
 
    @Override
    public void stopAllocCounting() {
        mBase.stopAllocCounting();
    }
 
    @Override
    public Bundle getAllocCounts() {
        return mBase.getAllocCounts();
    }
 
    @Override
    public Bundle getBinderCounts() {
        return mBase.getBinderCounts();
    }
 
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public UiAutomation getUiAutomation() {
        return mBase.getUiAutomation();
    }
 
    @Override
    public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Fragment fragment, Intent intent, int requestCode) {
        doMyOperation();
        return mBase.execStartActivity(who, contextThread, token, fragment, intent, requestCode);
    }
 
    @Override
    public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Fragment fragment, Intent intent, int requestCode, Bundle options) {
        doMyOperation();
        return mBase.execStartActivity(who, contextThread, token, fragment, intent, requestCode, options);
    }
 
    @Override
    public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode) {
        doMyOperation();
        return mBase.execStartActivity(who, contextThread, token, target, intent, requestCode);
    }
 
    @Override
    public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {
        doMyOperation();
        return mBase.execStartActivity(who, contextThread, token, target, intent, requestCode, options);
    }
 
    public void doMyOperation() {
 
    }
 
}

上面的doMyOperation是处理咱们业务逻辑的函数。

在Application里面进行初始化的类ActivityManager;

import android.app.Instrumentation;
import android.content.Context;
import android.os.Looper;
 
public class ActivityManager {
 
    private static ActivityManager SINGLETON;
 
    private Context mContext;
 
    private ActivityManager(Context context) {
        if (!isMainThread()) {
            return;
        }
 
        mContext = context;
        DelegateActivityThread delegateActivityThread = DelegateActivityThread.getSingletion();
        Instrumentation originInstrumentation = delegateActivityThread.getInstrumentation();
        if (!(originInstrumentation instanceof DelegateInstrumentation)) {
            DelegateInstrumentation delegateInstrumentation = new DelegateInstrumentation(originInstrumentation);
            delegateActivityThread.setInstrumentation(delegateInstrumentation);
        }
 
    }
 
    public static void init(Context context) {
        if (null != SINGLETON) {
            return;
        }
 
        SINGLETON = new ActivityManager(context);
    }
 
    private boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }
 
}

在Applicaiton进行初始化:

ActivityManager.init(this);

2.3 利用list自己管理的acitvity栈

无需多说。直接上代码。

import java.util.ArrayList;
import java.util.List;
 
import android.app.Activity;
 
/**
 * activity的管理栈,方便进行activity进行查找、处理
 *
 * 眼下只适用于单线程
 *
 * */
public class ActivityManager {
    private static ActivityManager SINGLETON = new ActivityManager();
    private static List<Activity> mAcitivityList = new ArrayList<Activity>();
 
    private ActivityManager() {
        if (null == mAcitivityList) {
            mAcitivityList = new ArrayList<Activity>();
        }
        mAcitivityList.clear();
    }
 
    public static ActivityManager getInstance() {
        if (null == SINGLETON) {
            SINGLETON = new ActivityManager();
        }
 
        return SINGLETON;
    }
 
    /**
     * activity入栈
     *
     * */
    public void addActivity(Activity activity) {
        staticUserPage(activity);
        mAcitivityList.add(activity);
    }
 
    /**
     * activity出栈
     *
     * */
    public void popActivity(Activity activity) {
        if (null == mAcitivityList) {
            return;
        }
        int total = mAcitivityList.size();
        if (total > 0) {
            mAcitivityList.remove(activity);
        }
    }
 
    /**
     * 获取栈顶的activity
     * */
    public Activity getTopActivity() {
        int total = mAcitivityList.size();
        if (total > 0) {
            Activity currentActivity = mAcitivityList.get(total - 1);
            return currentActivity;
        }
        return null;
    }
 
    /**
     * 清空全部的activity
     * */
    public void onExit() {
        if (null != mAcitivityList) {
            mAcitivityList.clear();
        }
        mAcitivityList = null;
    }
 
}

最后

从一个LauncherActivity到APP进程的activity,Activity的栈,在其中的工作大致如下:

  • Activity的启动一般可以通过startActivity()来进行,通过Instrumentation.execStartActivity(),最终会通知到AMS来进行Activity的启动。
  • AMS通过binder线程获知了需要启动Activity的任务,让ActivityStarter去完成activity的启动。
  • ActivityStarter在一连串的startActivity()调用过程中,为要启动的Activity创建了一个ActivityRecord。
  • 最后进入到startActivityUnchecked(),根据Activity的启动模式与启动标识符的不同进行不同的处理。
  • 如果这个Activity是新进程的Activity,将会通知AMS先进行APP进程的启动,APP进程的application启动完成后,会通知AMS,application初始完成,并将APP进程的binder代理交给AMS,AMS再通过ActivityStartSupervisor来realStartActivityLocked()->app.thread.scheduleLaunchActivity()来通知APP进程,可以启动activity了。
  • 如果这个Activity是本进程发起的启动,那么就会根据发起者Activity的启动模式以及新Activity的启动模式综合判断,是复用Activity接着调用newIntent()呢,还是新建一个Activity,然后也进入到realStartActivityLocked()->app.thread.scheduleLaunchActivity()来启动新的Activity.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/392153.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Gopro卡无法打开视频恢复方法

下边来看一个文件系统严重受损的Gopro恢复案例故障存储: 120G SD卡故障现象:客户正常使用&#xff0c;备份数据时发现卡无法打开&#xff0c;多次插拔后故障依旧。故障分析:Winhex查看发现0号分区表扇区正常&#xff0c;这应该是一个exfat格式的文件系统&#xff0c;但是逻辑盘…

【单目3D目标检测】MonoDDE论文精读与代码解析

文章目录PrefacePros and ConsAbstractContributionsPreliminaryDirect depth estimationDepth from heightPespective-n-point&#xff08;PnP&#xff09;PipelineDiverse Depth EstimationsRobust Depth CombinationOutput distributionSelecting and combining reliable de…

JVM-从熟悉到精通

JVM 机器语言 一个指令由操作码和操作数组成 方法调用等于一个压栈的过程 栈有 BP寄存器 和 SP寄存器来占用空间 BP -> Base Point 栈基址&#xff08;栈底&#xff09;SP -> Stack Point 栈顶 字节序用于规定数据在内存单元如何存放&#xff0c;二进制位的高位和低…

计算机组成原理|第二章(笔记)

目录第二章 计算机的发展及应用2.1 计算机的发展史2.1.1 计算机的生产和发展2.1.2 微型计算机的出现和发展2.1.3 软件技术的兴起与发展2.2 计算机的应用2.3 计算机的展望上篇&#xff1a;第一章&#xff1a;计算机系统概论 第二章 计算机的发展及应用 2.1 计算机的发展史 2.1.…

基于半车悬架的轴距预瞄与轴间预瞄仿真对比

目录 前言 1. 半车悬架模型 2.轴距预瞄(单点预瞄)和轴间预瞄(两点预瞄)原理与仿真分析 2.1轴距预瞄(单点预瞄) 2.1.1预瞄原理 2.2.轴间预瞄(两点预瞄) 2.2.1预瞄原理 2.3仿真分析 3.总结 前言 对于悬架而言&#xff0c;四个车轮实际的输入信息是受到前后延时以及左右相…

SpringCloud:Feign的使用及配置

目录 Feign的使用及配置 1、Feign替代RestTemplate 2、使用Fegin步骤 3、自定义配置 4、Feign使用优化 5、Feign的最佳实践方式 Feign的使用及配置 1、Feign替代RestTemplate RestTemplate方式远程调用的问题 问题&#xff1a; 1、代码可读性差&#xff0c;编程体验不同…

HTML基本概述

文章目录网站和网页浏览器的作用HTML标签元素注释乱码问题web系统是以网站形式呈现的&#xff0c;而前端是以网页形式呈现的。 网站和网页 网站&#xff08;web site&#xff09;&#xff1a;互联网上用于展示特定内容的相关网页的集合。也就是说&#xff0c;一个网站包含多个…

【预告】ORACLE Primavera P6 v22.12 虚拟机发布

引言 离ORACLE Primavera P6 EPPM最新系统 v22.12已过去了3个多月&#xff0c;应盆友需要&#xff0c;也为方便大家体验&#xff0c;我近日将构建最新的P6的虚拟环境&#xff0c;届时将分享给大家&#xff0c;最终可通过VMWare vsphere (esxi) / workstation 或Oracle virtua…

SQL 窗口函数详解

SQL窗口函数详解 窗口函数的主要作用是对数据进行分组排序、求和、求平均值、计数等。 一、窗口函数的基本语法 <分析函数> OVER ([PARTITION BY <列清单>] ORDER BY <排序用列清单> [ROWS BETWEEN 开始位置 AND 结束位置])理解窗口函数的基本语法&#xff…

opencv校正图像

目录1、前言2、例程2.1、代码2.2、效果口罩说明书网页3、按步骤分析转灰度图降噪 Canny边缘检测膨胀&#xff08;可视具体情况省略&#xff09;轮廓检索选取角度1、前言 我们用相机拍照时&#xff0c;会因为角度问题造成拍歪&#xff0c;会影响图像的识别&#xff0c;这时就需…

【PyTorch】教程:torch.nn.Hardtanh

torch.nn.Hardtanh 原型 CLASS torch.nn.Hardtanh(min_val- 1.0, max_val1.0, inplaceFalse, min_valueNone, max_valueNone) 参数 min_val ([float]) – 线性区域的最小值&#xff0c;默认为 -1max_val ([float]) – 线性区域的最大值&#xff0c;默认为 1inplace ([bool]) …

ABP(ASP.NET Boilerplate)配置整合使用Mysql数据库

ABP默认是支持sqlserver数据库的&#xff0c;但是这并不影响使用其他数据库&#xff0c;稍微配置一下就行了&#xff01;很简单——————————— 一、 卸载原来存在Sql Server的依赖包 在程序包管理控制台输入&#xff0c;选择EntityFrameworkCore 然后执行删除包的命令…

基于intel x86+fpga智能驾驶舱和高级驾驶辅助系统硬件设计(二)

系统功能架构及各模块功能介绍 智能驾驶舱和高级驾驶辅助系统是一个车载智能终端嵌入式平台&#xff0c;系统是一个能够运行 虚拟化操作系统的软件和硬件的综合体。本文的车载主机包括硬件主控处理器、电源管理芯 片、存储设备、输入输出控制器、数字仪表系统系统、后座娱乐系统…

抖音怎么合理安排直播内容|辽宁千圣文化

抖音主播们可以利用直播的方式达到带货的底模&#xff0c;那么做主播的话&#xff0c;就要利用好抖音主播中心&#xff0c;很多抖音用户却表示找不到抖音主播中心&#xff0c;那么怎么去看呢&#xff1f;跟着辽宁千圣文化小编来一起看看吧&#xff01;如何成为一名合格的主播&a…

【操作系统原理实验】调度算法模拟实现

选择一种高级语言如C/C等&#xff0c;模拟实现调度算法完成资源分配与回收的过程。2) 自定义PCB等核心数据结构&#xff1b;3) 利用列表、队列等容器类或者其他数据结构管理PCB,完成相应调度算法的模拟&#xff1b;4) 实现外围一些命令如创建进程、查看进程、关闭进程等&#x…

Spacedesk软件推荐,让你的平板也变成电脑的副屏

我的设备&#xff1a; 电脑:戴尔G15 5511、i7-11800H、Windows 11、RTX3060 平板&#xff1a;荣耀V6、麒麟985、安卓10、分辨率2000*1200&#xff08;手机也行&#xff0c;我用的平板&#xff09; 实际使用&#xff1a; 先给放一张实际使用的照片 可以让平板变成电脑的副屏…

28 位委员出席,龙蜥社区第 15 次运营委员会会议顺利召开

2 月 24 日&#xff0c;龙蜥社区在海光召开了第 15 次运营委员会会议&#xff0c;本次会议由统信软件运营委员会委员崔开主持。来自 Arm、阿里云、飞腾、红旗软件、海光、Intel、龙芯、联通软研院、浪潮信息、普华基础软件、统信软件、万里红、移动、中科方德等理事单位的 28 位…

echarts--提示框显示不全问题记录

最近接手一个同事之前做的网页&#xff0c;发现里面使用echarts来绘制各类图表&#xff1b;有2个问题一个是提示框显示不全&#xff0c;另一个就是绘制总是有部分数据显示不全。后者就是div宽度问题。。。无语&#xff0c;说下前面一个问题吧&#xff0c;记录一下。 tooltip组…

【redis学习篇】主从哨兵集群架构详解

一、Redis主从架构 1.1 redis主从架构搭建 1、复制一份redis.conf文件 2、将相关配置修改为如下值&#xff1a; port 6380 pidfile /var/run/redis_6380.pid # 把pid进程号写入pidfile配置的文件 logfile "6380.log" dir /usr/local/redis-5.0.3/data/6380 # 指…

Linux基础命令-groupmems管理组群的成员

Linux-usermod修改用户 Linux-useradd创建用户 Linux-userdel删除用户 Linux基础命令-chown修改文件属主 Linux基础命令-chmod修改文件权限 groupmems 命令介绍 先来看看这个命令的帮助信息是什么概念 NAME groupmems - administer members of a user’s primary group group…