Activity启动梳理

ContextImpl为Context抽象类的具体实现,且持有ActivityThread的实例,当我们发起启动Activity的动作


/*framework/base/core/java/android/app/ContextImpl.java*/
@Override
    public void startActivity(Intent intent, Bundle options) {
        warnIfCallingFromSystemProcess();
        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
            throw new AndroidRuntimeException(
                    "Calling startActivity() from outside of an Activity "
                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
                    + " Is this really what you want?");
        }
        mMainThread.getInstrumentation().execStartActivity(
            getOuterContext(), mMainThread.getApplicationThread(), null,
            (Activity)null, intent, -1, options);
    }

首先进行参数分析

     framework/base/core/java/android/app/Instrumentation.java

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    if (am.match(who, null, intent)) {
                        am.mHits++;
                        if (am.isBlocking()) {
                            return requestCode >= 0 ? am.getResult() : null;
                        }
                        break;
                    }
                }
            }
        }
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess();
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
        }
        return null;
    }
    1. Context who: getOuterContext() —— 此处获取的实际就是当前发起Intent意图的Activity或Service的Context对象。在ContextImpl中维护着一个private Context mOuterContext;对象,此对象的实例化是构造函数,同时也提供了set和get方法来设置和获取此对象。

private Context mOuterContext;

......

ContextImpl() {
    mOuterContext = this;
}

/**
 * Create a new ApplicationContext from an existing one.  The new one
 * works and operates the same as the one it is copying.
 *
 * @param context Existing application context.
 */
public ContextImpl(ContextImpl context) {
    mPackageInfo = context.mPackageInfo;
    mBasePackageName = context.mBasePackageName;
    mOpPackageName = context.mOpPackageName;
    mResources = context.mResources;
    mMainThread = context.mMainThread;
    mContentResolver = context.mContentResolver;
    mUser = context.mUser;
    mDisplay = context.mDisplay;
 *   mOuterContext = this;
    mDisplayAdjustments.setCompatibilityInfo(mPackageInfo.getCompatibilityInfo());
}

......

final void setOuterContext(Context context) {
    mOuterContext = context;
}

final Context getOuterContext() {
    return mOuterContext;
}

ContextImpl的初始化,引申出的就是App进程首次创建 以及新的Activity和Service对象的初始化过程。<此过程后续单独开贴说明>

2.  IBinder contextThread = mMainThread.getApplicationThread()。  mMainThread即为应用的主UI线程,有且仅有一个。

ActivityThread创建完成后,会进行attach操作,将App进程的Binder通信句柄注册给ActivityManagerService,这样后续AMS即可通过IBinder向新启动的App发送消息。

/*framework/base/core/java/android/app/ActivityThread.java*/

final ApplicationThread mAppThread = new ApplicationThread();

private void attach(boolean system) {
    ......

    if (!system) {
        ......

        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        IActivityManager mgr = ActivityManagerNative.getDefault();
        try {
            mgr.attachApplication(mAppThread);
        } catch (RemoteException ex) {
            // Ignore
        }
    } 
}
客户端App获取到的mgr为ActivityManagerProxy代理,调用attachApplication时向AMS发送了 ATTACH_APPLICATION_TRANSACTION进程间通信

public void attachApplication(IApplicationThread app) throws RemoteException
    {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(app.asBinder());
        mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
        reply.readException();
        data.recycle();
        reply.recycle();
    }

当AMS作为Server端接收到请求后,得到app,此时拿到的app为proxy代理(asInterface方法会进行判断,如果为同一进程,则返回实体对象;反之,返回IBinder proxy代理)

case ATTACH_APPLICATION_TRANSACTION: {
            data.enforceInterface(IActivityManager.descriptor);
            IApplicationThread app = ApplicationThreadNative.asInterface(
                    data.readStrongBinder());
            if (app != null) {
                attachApplication(app);
            }
            reply.writeNoException();
            return true;
        }

继续追踪attachApplication的具体实现,ActivityManagerService继承了ActivityManagerNative,并实现了其具体方法?

 framework/base/services/java/com/android/server/am/ActivityManagerService.java

@Override
    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
    }
attachApplicationLocked方法的实现较为复杂,大致包括通过pid获取调用进程的ProcessRecord, 等等一系列判断,后续再做补充,至此,AMS便持有了与App通信的IApplicationThread Proxy代理,后续对于App的一切调度都通过代理进行进程间通信。


3. IBinder token=null

4.Fragment/Activity target  :target为Activity时直接设为null,Fragment时设置为target.mWho

5.Intent intent:设置了class参数等,ams会据此获取到目标Activity的信息,从而进行跳转。

6. int requestCode:直接设置为-1,startActivityForResult时需要这个值返回。

7. Bundle options:设置附加信息,没有时直接设为null。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值