必威体育Betway必威体育官网
当前位置:首页 > IT技术

startActivity()详解

时间:2019-08-26 13:40:00来源:IT技术作者:seo实验室小编阅读:55次「手机版」
 

activity

startActivity()详解

1.首先我们先要知道Activity 父亲是context ,Context 是个抽象类,ContextImpl 是Context 具体实现类.ContextWrAPPer也是继承于Context ,Contextwrapper使用代理方式调用ContextImpl.

static ContextImpl getImpl(Context context) {
    Context nextContext;
    while ((context instanceof ContextWrapper) &&
            (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
        context = nextContext;
    }
    return (ContextImpl)context;
}

不管你在那个页面调用startActivity()最终都会调用ContextImpl的startActivity()方法,所有这里我们直接从ContextImpl的startActivity()入手如下:

class ContextImpl extends Context {
 
@Override
public void startActivity(intent intent) {
  //判断是不是同一个进程
    warnIfcallingFromSystemProcess();
    startActivity(intent, null);
   }
 }
//也可以用两个产生的方法,一个参数也是调用的两个参数的方法
@Override
public void startActivity(Intent intent, Bundle options) {
   //判断是不是同一个进程
    warnIfCallingFromSystemProcess();
    //这里 mMainThread 就是 activitythread
   mMainThread.getInstrumentation().execStartActivity(
            getOuterContext(), mMainThread.getApplicationThread(), null,
            (Activity) null, intent, -1, options);
}

不管你调用startActivity一个参数方法还是两个参数方法,它都会去调用两个参数的 startActivity,先判断是不是相同的 UID 然后在执行execStartActivity,mMainThread就是ActivityThread,ActivityThread调用createSystemContext创建ContextImpl时候把ActivityThread传过来.

Instrumentation 是用来管理Activtiy生命周期的一个对象,主要负责呼叫Activity的生命周期.Instrumentation 赋值是在启动SystemServer进程通过createSystemContext

//ActivityThread调用getInstrumentation()
public Instrumentation getInstrumentation()
{
    return mInstrumentation;
}
private void createSystemContext() {
  //创建ActivityThread
    ActivityThread activityThread = ActivityThread.systemMain();
   //创建 ContextImpl
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
}
//创建ActivityThread
public static ActivityThread systemMain() {
   //创建ActivityThread
    ActivityThread thread = new ActivityThread();
   //执行 attach(true)默认是true
    thread.attach(true);
    return thread;
}
//attach 方法执行 上面attach(true)所以!true
//就是走else 
private void attach(boolean system) {
    sCurrentActivityThread = this;
    mSystemThread = system;
   //
    if (!system) {
    
    } else {
      //创建Instrumentation
            mInstrumentation = new Instrumentation();
            ContextImpl context = ContextImpl.createAppContext(
                    this, getSystemContext().mPackageInfo);
            MinitialApplication = context.mPackageInfo.makeApplication(true, null);
            mInitialApplication.onCreate();

   }

SystemServer进程通过createSystemContext创建ActivityThread,并用ActivityThread的attach(true)的方法创建了Instrumentation,ContextImpl,makeApplication ,并执行Application的oncreate方法,这里我们知道了attach(true)是用来创建Instrumentation我们看到startActivity之后调用ActivityThread的getInstrumentation()方法在执行execStartActivity方法如下:

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestcode,   options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
 
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        int result = activitymanagerNative.getDefault()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfneeded(who.getcontentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new runtimeexception("Failure from system", e);
    }
    return null;
}

最主要的一个方法就是 ActivityManagerNative.getDefault() .startActivity() 这个方法主要是给通过Binder来通知系统我要调到那个Activity中,

static public IActivityManager getDefault() {
    return gDefault.get();
}
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
    protected IActivityManager create() {
        IBinder b = ServiceManager.getService("activity");
        if (false) {
            Log.v("ActivityManager", "default service binder = " + b);
        }
        IActivityManager am = asInterface(b);
        if (false) {
            Log.v("ActivityManager", "default service = " + am);
        }
        return am;
    }
};

IActivityManager am = asInterface(b) 这个方法开发过aidl应该不陌生,就是负责进程通信

static public IActivityManager asInterface(IBinder obj) {
    if (obj == null) {
        return null;
    }
    IActivityManager in =
        (IActivityManager)obj.querylocalInterface(descriptor);
    if (in != null) {
        return in;
    }

    return new ActivityManagerProxy(obj);
}

ActivityManagerNative.getDefault() 启动就是返回一个IActivityManager ,IActivityManager是一个接口 ActivityManagerProxy是IActivityManager具体实现类,ActivityManagerNative.getDefault() .startActivity()就是调用 ActivityManagerProxy的startActivity方法

public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
        String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, profilerInfo profilerInfo, Bundle options) throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    data.writeInterfaceToken(IActivityManager.descriptor);
    data.writeStrongBinder(caller != null ? caller.asBinder() : null);
    data.writeString(callingPackage);
    intent.writeToParcel(data, 0);
    data.writeString(resolvedType);
    data.writeStrongBinder(resultTo);
    data.writeString(resultWho);
    data.writeInt(requestCode);
    data.writeInt(startFlags);
    if (profilerInfo != null) {
        data.writeInt(1);
        profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
    } else {
        data.writeInt(0);
    }
    if (options != null) {
        data.writeInt(1);
        options.writeToParcel(data, 0);
    } else {
        data.writeInt(0);
    }
    mRemote.transact(START_ACTIVITY_transaction, data, reply, 0);
    reply.readException();
    int result = reply.readInt();
    reply.recycle();
    data.recycle();
    return result;
}

ActivityManagerProxy的startActivity方法 最重要的一句话是就是 mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);这就话就是 Binder通信就核心的一句话,主要负责将当前进程信息传递到其它进程

通过Binder驱动程序就进入到ActivityManagerService的startActivity函数来了

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            Userhandle.getCallingUserId());
}

ActivityManagerService 中调用startActivity 继续调用startActivityAsUser

final ActivityStarter mActivityStarter;@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
  
        int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voicesession, voiceInteractor,
                resultTo, resultWho, requestCode, callingPid,
                callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                inTask);

        return res;
    }
}

继续调用 startActivityLocked

final int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
        String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
        String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
        ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
        ActivityRecord[] outActivity, ActivityStacksupervisor.ActivityContainer container,
        TaskRecord inTask) {
    int err = ActivityManager.START_SUCCESS;


    try {
        mService.mWindowManager.deferSurfacelayout();
        err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true, options, inTask);
    } finally {
        mService.mWindowManager.continueSurfaceLayout();
    }


    return err;
}

继续调用startActivityUnchecked

private final ActivityStackSupervisor mSupervisor;

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {

if (mDoResume) {
    mSupervisor.resumeFocusedStackTopActivityLocked();
}
   
    return START_SUCCESS;
}

这里的mSupervisor 是 ActivityStackSupervisor 继续调用resumeFocusedStackTopActivityLocked

ActivityStackSupervisor类ActivityStack类配合使用. ActivityStackSupervisor负责管理Task和Stack, 而ActivityStack负责管理在Stack和Task中的Activity. 因此, 对于Stack和Task的操作, AMS使用ActivityStackSupervisor进行管理; 对于Activity的操作, AMS使用ActivityStack进行管理. 两者相互调用, 最终完成启动Activity.

ActivityStackSupervisor类ActivityStack类的调用流程:

  1. ActivityStackSupervisor#resumeFocusedStackTopActivityLocked
  2. ActivityStack#resumeTopActivityUncheckedLocked
  3. ActivityStack#resumeTopActivityInnerLocked
  4. ActivityStackSupervisor#startSpecificActivityLocked

核心在于ActivityStack类的resumeTopActivityInnerLocked方法, 根据ActivityRecord和ActivityOptions完成Activity的切换, 移至栈顶, 最后调用ActivityStackSupervisor类的startSpecificActivityLocked方法, 执行启动.

ActivityStackSupervisor类的startSpecificActivityLocked方法调用realStartActivityLocked方法, 执行真正的启动Activity.

boolean resumeFocusedStackTopActivityLocked() {
    return resumeFocusedStackTopActivityLocked(null, null, null);
}
boolean resumeFocusedStackTopActivityLocked(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    if (targetStack != null && isFocusedStack(targetStack)) {
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
    if (r == null || r.state != RESUMED) {
        mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
    }
    return false;
}
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {

    boolean result = false;
    try {
       
        result = resumeTopActivityInnerLocked(prev, options);
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }
    return result;
}
ActivityStackSupervisor mStackSupervisor
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

mStackSupervisor.startSpecificActivityLocked(next, true, false);

    return true;
}

mStackSupervisor 这里的 mStackSupervisor 就ActivityStackSupervisor  执行startSpecificActivityLocked

void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);

    r.task.stack.setLaunchTime(r);

    if (app != null && app.thread != null) {
        try {
         
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
     
        }
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {

        app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                System.identityHashCode(r), r.info, new configuration(mService.mConfiguration),
                new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
                task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);

     
    } catch (RemoteException e) {
     
    }

    return true;
}

 内部类IApplicationThread的实现是ApplicationThread, 而ApplicationThread是ActivityThread的内部类, 即使用ApplicationThread类的scheduleLaunchActivity方法处理Activity启动ApplicationThread是ActivityThread

@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
        ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
        CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
        int procState, Bundle state, PersistableBundle persistentState,
        List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
        boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

    updateProcessState(procState, false);

    ActivityClientRecord r = new ActivityClientRecord();

    r.token = token;
    r.ident = ident;
    r.intent = intent;
    r.referrer = referrer;
    r.voiceInteractor = voiceInteractor;
    r.activityInfo = info;
    r.compatInfo = compatInfo;
    r.state = state;
    r.persistentState = persistentState;

    r.pendingResults = pendingResults;
    r.pendingIntents = pendingNewIntents;

    r.startsNotResumed = notResumed;
    r.isForward = isForward;

    r.profilerInfo = profilerInfo;

    r.overrideConfig = overrideConfig;
    updatePendingConfiguration(curConfig);

    sendmessage(H.LAUNCH_ACTIVITY, r);
}
public void handleMessage(Message msg) {
    if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
    switch (msg.what) {
        case LAUNCH_ACTIVITY: {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
            final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

            r.packageInfo = getPackageInfoNoCheck(
                    r.activityInfo.applicationInfo, r.compatInfo);
            handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        } break;

通过 sendMessage(H.LAUNCH_ACTIVITY, r);发送到handleMessage 执行 handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");函数

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
  
    Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        
        handleresumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        
    }
}

执行performLaunchActivity 方法

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

    Activity activity = null;

    try {
        //创建Application
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        if (activity != null) {
            //执行 activity.attach 方法
            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);

          //呼叫OnCreate
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
        
            r.activity = activity;
            r.stopped = true;
            if (!r.activity.mFinished) {
                activity.performStart();
                r.stopped = false;
            }
            if (!r.activity.mFinished) {
                if (r.isPersistable()) {
                    if (r.state != null || r.persistentState != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                r.persistentState);
                    }
                } else if (r.state != null) {
                    mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                }
            }
            if (!r.activity.mFinished) {
                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state,
                            r.persistentState);
                } else {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onPostCreate()");
                }
            }
        }
        r.paused = true;

        mActivities.put(r.token, r);

    } catch (SuperNotCalledException e) {
        throw e;

    } catch (Exception e) {
    
    }

    return activity;
}
public void callActivityOnCreate(Activity activity, Bundle icicle,
        PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState);
    postPerformCreate(activity);
}
//执行 Activity  onCreate
final void performCreate(Bundle icicle) {
    restoreHasCurrentpermissionRequest(icicle);
     (icicle);
    mActivityTransitionState.readState(icicle);
    performCreateCommon();
}

相关阅读

Android startActivityForResult基本用法

从A页面使用startActivityForResult()跳转到B页面,B页面点击返回时将新写入的值传回到A页面。 MainActivity: public class MainAct

更优雅的使用startActivityForResult及权限请求

一、问题所在 Android页面之前的数据回传我们一般使用startActivityForResult来处理,这没什么问题,但问题就在于我们所有的处理结

分享到:

栏目导航

推荐阅读

热门阅读