zoukankan      html  css  js  c++  java
  • Activity的生命周期是谁调用的?*

     我们知道Activity的生命周期包括onCreate、onStart、onResume、onRestart、onStop、onDestory、onSaveInstanceState、onRestoreInstanceState等等, 那么是谁调用了它呢?    

    答:是ActivityThread调度的, 具体逻辑封装在Instrumentation类里。 好好看看这2个类就明白了。

            Instrumentation类封装了Activity各个生命周期的方法,  所以想办法替换mInstrumentation参数就可以了。 因为sCurrentActivityThread是单例的,所以hook它就OK了。

    public class TheApplication extends Application {
         .....
     
        private class InstrumentationProxy extends Instrumentation {
            private Instrumentation oldInstance;
     
            public InstrumentationProxy(Instrumentation instrumentation) {
                oldInstance = instrumentation;  //取消hook时使用
            }
     
            @Override
            public void callActivityOnResume(Activity activity) {
                Log.d("brycegao", activity.getClass().toString() + " 执行了onPause方法");
                super.callActivityOnResume(activity);
            }
     
            @Override
            public void callActivityOnStop(Activity activity) {
                Log.d("brycegao", activity.getClass().toString() + " 执行了onStop方法");
                super.callActivityOnStop(activity);
            }
        }
     
        @Override
        public void onCreate() {
            super.onCreate();
     
            try {
                Class<?> clz = Class.forName("android.app.ActivityThread");
                Method method = clz.getDeclaredMethod("currentActivityThread");
                method.setAccessible(true);
                Object currentThread = method.invoke(null);
     
                Field mInstrumentationField = clz.getDeclaredField("mInstrumentation");
                mInstrumentationField.setAccessible(true);
                Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentThread);
     
                Instrumentation proxy = new InstrumentationProxy(mInstrumentation);
                mInstrumentationField.set(currentThread, proxy);
            } catch (Exception ex) {
     
            }
            .....
         }
    }


    运行看看效果:

    ActivityThread有个成员变量mH, 它是干嘛用的?

       final H mH = new H();

       类H继承于Handler, mH是为了实现异步操作,所有操作都放到主线程MessageQueue队列里实现。  比如A进程打开B进程的Activity, 通过Binder机制由ActivityManagerProxy执行启动activity的逻辑, 但这个操作是异步的。 A进程相当于做个触发事件, 不会阻塞等待B进程的activity启动。

  • 相关阅读:
    Dapper and Repository Pattern in MVC
    在linux中使用多个redis端口来构建redis集群
    搭建Sql Server AlwaysOn 视频教程
    支付宝支付插件使用文档
    NopCommerce添加事务机制
    NopCommerce(3.9)作业调度插件
    微信扫码支付插件使用文档
    生成HTML表格的后台模板代码
    json字符串和字典类型的相互转换
    NopCommerce适应多数据库方案
  • 原文地址:https://www.cnblogs.com/chenxibobo/p/9640085.html
Copyright © 2011-2022 走看看