IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android UI 绘制流程源码解析1(app启动流程) -> 正文阅读

[移动开发]Android UI 绘制流程源码解析1(app启动流程)

一 app运行入口(ActivityThread)

了解过app的启动流程的之后,我们都知道app的主线程(UI线程)其实是在创建app进程的时候随之创建的,在这个线程里,有一个Handle,就是ActivityThread(注意它的名字看起来像是线程,但是根据它的继承结构来看,它其实是一个handle),负责app和Ams的通信;当我们打开一个应用的时候,就会从ActivityThread的main()方法里进入,接下来我们来看看ActivityThread的**main()**方法。

public static void main(String[] args) {

		//获取looper
        Looper.prepareMainLooper();  
        //创建ActivityThread的实例
        ActivityThread thread = new ActivityThread();
        //这里是关键,待会我们仔细看看这个方法,这里只要知道它是继续往后执行的关键即可
        thread.attach(false, startSeq);
        //开始轮询
        Looper.loop();

    }

main()方法不是很长,我省略了一些无关紧要的判断,留下了关键的代码,从上面我们也能看出来ActivityThread其实就是一个handle(具体handle原理就不多说了),接着我们重点来看一下**attach()**方法
在这讲attach()方法之前,我们来普及一下三个关键的变量

public final class ActivityThread extends ClientTransactionHandler {


final H mH = new H();  1

final ApplicationThread mAppThread = new ApplicationThread(); 2

Instrumentation mInstrumentation; 3
}
  1. ActivityThread 一个继承handler的一个内部类,用来接收AMS通过AppliactionThread调用ActivityThread的内部方法,来实现app的运行控制(比如Activity的生命周期方法的调用等)
  2. AMS和ActivityThread沟通的桥梁,ActivityThread获取AMS的代理类,然后将ApplicationThread的引用传递进代理类的相对应的方法里,这样AMS就拥有了ApplicationThread的引用,可以调用ActivityThread里的方法
  3. 这个其实是一个统一管理生命周期方法的类,也就是说ActivityThread不会直接调用某一个Activity的生命周期方法,而是通过这个类的引用去调用

Ok,我们回到main()方法里调用的attach()这个方法里来

ActivityThread.java —> main() -----> attach()

  private void attach(boolean system, long startSeq) 
  {

         	//获得Ams的代理类
            final IActivityManager mgr = ActivityManager.getService();
            try {
            	//调用AMS里的方法,将ApplicationThread(mAppThread传递进去)
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
           
 }

attach() --> AMS.attachApplication()

  private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq){
         //这个其实是一个数据类,用来记录当前app的进程信息   
		ProcessRecord app;
		//接下来就是根据这个数据类进行初始化工作,从AMS里获取到进程信息且赋值到这个类中
		//最终回调ApplicationThread里的bindApplication
            thread.bindApplication(processName, appInfo, providers,
                        app.instr.mClass,
                        profilerInfo, app.instr.mArguments,
                        app.instr.mWatcher,
                        app.instr.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);

}

AMS.attachApplicationLocked 里调用
ActivityThread.ApplicationThread.bindApplication()

public final void bindApplication(String processName, ApplicationInfo appInfo,
        List<ProviderInfo> providers, ComponentName instrumentationName,
        ProfilerInfo profilerInfo, Bundle instrumentationArgs,
        IInstrumentationWatcher instrumentationWatcher,
        IUiAutomationConnection instrumentationUiConnection, int debugMode,
        boolean enableBinderTracking, boolean trackAllocation,
        boolean isRestrictedBackupMode, boolean persistent, Configuration config,
        CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
        String buildSerial, boolean autofillCompatibilityEnabled) {

				//将从AMS里获取到的app进程信息封装到AppBindData这个数据类中
	         AppBindData data = new AppBindData();
            data.processName = processName;
            data.appInfo = appInfo;
            data.providers = providers;
            data.instrumentationName = instrumentationName;
            data.instrumentationArgs = instrumentationArgs;
            data.instrumentationWatcher = instrumentationWatcher;
            data.instrumentationUiAutomationConnection = instrumentationUiConnection;
            data.debugMode = debugMode;
            data.enableBinderTracking = enableBinderTracking;
            data.trackAllocation = trackAllocation;
            data.restrictedBackupMode = isRestrictedBackupMode;
            data.persistent = persistent;
            data.config = config;
            data.compatInfo = compatInfo;
            data.initProfilerInfo = profilerInfo;
            data.buildSerial = buildSerial;
            data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
            //接着通过上面说过的mh这个handle发送消息
            sendMessage(H.BIND_APPLICATION, data);
}

我们直接来看handleMesage()这个方法

public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case BIND_APPLICATION:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                    AppBindData data = (AppBindData)msg.obj;
                    //这里调用了ActivityThread里的方法,传入刚才的数据类AppBindData
                    handleBindApplication(data);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
}

ActivityThread.handleBindApplication()

   private void handleBindApplication(AppBindData data) {

	
 final ClassLoader cl = instrContext.getClassLoader();
 	//通过反射创建上面说过的Instrumentation这个监管类
	mInstrumentation = (Instrumentation)cl.loadClass(data.instrumentationName.getClassName()).newInstance();
	//Application变量申明
Application app;

 app = data.info.makeApplication(data.restrictedBackupMode, null){

//这个方法通过反射创建了Application,此时我们熟悉的Application在这里就算创建成功了
	  ContextImpl appContext = 	ContextImpl.createAppContext(mActivityThread, this);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
}

  //将创建的Application传入到instrumentation里去,去执行其生命周期方法
  instrumentation.callApplicationOnCreate(app){
    //显而易见了把,这里直接调用了Application的onCreate的生命周期方法,等一下了解Activity的创建的时候也会进一步让大家了解到instrumentation的用途
	public void callApplicationOnCreate(Application app) {
        app.onCreate();
    }
};		
}

创建完Application之后,我们接下来肯定是要创建Activity了,很显然,也是跟创建Application有点不一样,Application的创建我们需要从Ams里获取到Application的信息,进而通过反射创建实例,接着传入instrumentation执行它的生命周期方法,而Activity则是通过事务来创建;我们回到Ams的attachApplicationLocked ()方法中去,在创建了Application之后,还有创建Activity的逻辑
AMS.attachApplicationLocked ()

  private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq){
         //这个其实是一个数据类,用来记录当前app的进程信息   
		ProcessRecord app;
		//接下来就是根据这个数据类进行初始化工作,从AMS里获取到进程信息且赋值到这个类中
		//最终回调ApplicationThread里的bindApplication
            thread.bindApplication(processName, appInfo, providers,
                        app.instr.mClass,
                        profilerInfo, app.instr.mArguments,
                        app.instr.mWatcher,
                        app.instr.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);


     if (normalMode) {
            try {
            	//mStackSupervisor其实就是ActivityStackSupervisor ,这个ActivityStack和我们理解的Activity的stack管理不是同一个概念,
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }

}

ActivityStackSupervisor .attachApplicationLocked(app).

 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        final String processName = app.processName;
        boolean didSomething = false;
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
            for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
                final ActivityStack stack = display.getChildAt(stackNdx);
                if (!isFocusedStack(stack)) {
                    continue;
                }
                stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
                //获得顶层的ActivityRecord,这个类其实也是一个数据类,用来记录Activity的信息的
                final ActivityRecord top = stack.topRunningActivityLocked();
                final int size = mTmpActivityList.size();
                for (int i = 0; i < size; i++) {
                    final ActivityRecord activity = mTmpActivityList.get(i);
                    //根据activity的信息判断是否是属于这个app的
                    if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                            && processName.equals(activity.processName)) {
                        try {
                        //通过for循环将每个activity的信息传到此方法中,同时还加入了app界面里首个Activity的标志位(MainActivity)
                            if (realStartActivityLocked(activity, app,
                                    top == activity /* andResume */, true /* checkConfig */)) {
                                didSomething = true;
                            }
                        } 

    }

ActivityStackSupervisor .realStartActivityLocked()

        final boolean realStartActivityLocked (ActivityRecord r,
                ProcessRecord app,boolean andResume, boolean checkConfig) 
		 throws RemoteException {
            //创建事务
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
            //添加事务的回调接口  ,这个重点关注一下,下面会重点提到        
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), arg[]);
            // Schedule transaction.  提交事务给AMS的LifecycleManager  (ClientLifecycleManager)  
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);


        }

AMS.getLifecycleManager() --> ClientLifecycleManager.scheduleTransaction()

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    transaction.schedule();
    if (!(client instanceof Binder)) {
        transaction.recycle();
    }
}

ClientTransaction .schedule()
**

public void schedule() throws RemoteException {
		//这个mClient其实就是ApplicationThread,在实例化事务ClientTransaction的时候传入,这里最终就调用了ApplicationThread里的scheduleTransaction()方法
        mClient.scheduleTransaction(this);
    }

Ok,我们从AMS里回到ActivityThread里来
ActivityThread.ApplicationThread.scheduleTransaction()

   @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }

ActivityThread.scheduleTransaction()

 public abstract class ClientTransactionHandler 
 {
 	//ActivityThread继承ClientTransactionHandler
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    }

ActivityThread.mH.handleMessage()

        mH {

            handleMessage() {

                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    //从名字看就知道它是事务的执行器TransactionExecutor
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        transaction.recycle();
                    }

            }
        }

TransactionExecutor.execute()

public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {
        final IBinder token = transaction.getActivityToken();
        executeCallbacks(transaction);
        executeLifecycleState(transaction);
        mPendingActions.clear();
        log("End resolving transaction");
    }

 public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
     //通过for循环一次从transaction里获取callback,执行其execute方法
     //这个callback大家应该该有印象吗,就是我们在创建事务的实例的时候,会通过for循环遍历ActivityRecord,依次创建LaunchActivityItem (ClientTransactionItem 的子类)
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i)
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            }
        }
    }

    }

LaunchActivityItem .execute()

public class LaunchActivityItem extends ClientTransactionItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
     //将ActivityRecord里的信息封装进入ActivityClientRecord
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client);
         //client就是ActivityThead
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

}

ActivityThead.handleLaunchActivity()

 @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,


        final Activity a = performLaunchActivity(r, customIntent);
    }

ActivityThead.performLaunchActivity()

 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }


        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
        //同样通过反射创建activity的实例
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
                appContext.setOuterContext(activity);
		//这个方法很重要,里面有UI绘制的逻辑,下一篇仔细来看一下里面的源码
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
                if (r.isPersistable()) {
                //通用将创建的activity的实例传入mInstrumentation
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
         
    }

这里最终把activity实例传入到mInstrumentation里去,里面会调用activity的onCreate()方法,此时activity就已经创建成功了。接下来看一下流程图加深一下印象
在这里插入图片描述

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-09-27 14:12:28  更:2021-09-27 14:15:06 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 20:01:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码