Android进阶(二)应用进程启动

一、应用程序进程创建
1、 应用进程请求
  • Zygote进程会创建一个Socket,用来等待AMS请求创建应用进程。
  • ActivityManagerService会通过调用startProcessLocked来发送请求。
  • 接收到请求后,Zygote进程会fork自身创建应用进程。
2、接收创建请求

通过ZygoteServer的runSelectLoop方法处理创建进程的请求–>
ZygoteConnection的runOnce处理请求数据–>
ZygoteInit的zygoteInit方法中创建Binder线程池–>
RuntimeInit的invokeStaticMain方法

private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
        throws Zygote.MethodAndArgsCaller {
    Class<?> cl;
    
    try {
        //通过反射创建了ActivityThread对象
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }

    Method m;
    try {
        //获取ActivityThread对象的main方法
        m = cl.getMethod("main", new Class[] { String[].class });
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(
                "Missing static main on " + className, ex);
    } catch (SecurityException ex) {
        throw new RuntimeException(
                "Problem getting static main on " + className, ex);
    }
    ......
    throw new Zygote.MethodAndArgsCaller(m, argv);
}

最后抛出一个MethodAndArgsCaller异常,被ZygoteInit的main方法处理–>
Zygote的run方法

public void run() {
    try {
        mMethod.invoke(null, new Object[] { mArgs });
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    } catch (InvocationTargetException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else if (cause instanceof Error) {
            throw (Error) cause;
        }
        throw new RuntimeException(ex);
    }
}

通过反射调用了ActivityThread的main方法

3、ActivityThread
public static void main(String[] args) {
    ......
    //创建Looper
    Looper.prepareMainLooper();
    
    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    //Looper开始处理消息
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值