Android点将台:颜值担当[-Activity-],Android学习教程


3:singleTask模式:对象唯一栈

整个栈中没有相同的实例,两次相同实例之间的Activity会被杀死(够霸道,我喜欢)
测试:Activity1为standard, Activity2 为singleTask

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CCYgBHw3-1630918359666)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95cb8af191c?imageView2/0/w/1280/h/960/ignore-error/1)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Yg8tOqOH-1630918359668)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95ccdc9544e?imageslim)]

依次打开Activity1、2、2、1、2
E/TASK_ID: Activity1 Task id is 94
E/TASK_ID: Activity2 Task id is 94
E/TASK_ID: Activity1 Task id is 94
E/TASK_ID: Activity1 销毁
依次返回
E/TASK_ID: Activity2 销毁
E/TASK_ID: Activity1 销毁 

4:singleInstance 单独实例栈

启用一个新的活动栈来管理这个活动(够豪,够任性)
测试:Activity1为standard, Activity2 singleInstance

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4NU9IDZx-1630918359669)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95ceb75173d?imageView2/0/w/1280/h/960/ignore-error/1)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6vdnWlYe-1630918359671)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95cd0fed3c9?imageslim)]

依次打开Activity1、2、2、1、2
 E/TASK_ID: Activity1 Task id is 115
 E/TASK_ID: Activity2 Task id is 116
 E/TASK_ID: Activity1 Task id is 115
依次返回
 E/TASK_ID: Activity2 销毁
 E/TASK_ID: Activity1 销毁
 E/TASK_ID: Activity1 销毁 

注意一点:
singleTask模式和singleTop模式时,非第一次启动,不会调用onCreate方法!   
但会走onNewIntent方法 

四、Activity的跳转动画

这里只是简单的四个平移动画,需要的更酷炫的效果道理是一样的
关于动画的更多知识,这里不废话了,可详见:Android 动画 Animator 家族使用指南

默认修改

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ajDLCHy5-1630918359674)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95cba698d0a?imageView2/0/w/1280/h/960/format/png/ignore-error/1)]

|

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PW67vuWU-1630918359675)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95cc5c4fb8d?imageView2/0/w/1280/h/960/format/png/ignore-error/1)]

|


1.代码实现Activity跳转

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s1MKUfIz-1630918359675)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95cee8f8430?imageView2/0/w/1280/h/960/ignore-error/1)]

/**
 * 作者:张风捷特烈<br></br>
 * 时间:2019/1/20/020:18:25<br></br>
 * 邮箱:1981462002@qq.com<br></br>
 * 说明:红色Activity
 */
class RedActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val view = View(this)
        view.setBackgroundColor(Color.RED)
        title = "RedActivity"
        view.setOnClickListener { v ->
            startActivity(Intent(this, BlueActivity::class.java))
            overridePendingTransition(R.anim.open_enter, R.anim.open_exit);
        }
        setContentView(view)
    }
    override fun onBackPressed() {
        super.onBackPressed()
        overridePendingTransition(R.anim.open_enter, R.anim.open_exit);
    }
}

/**
 * 作者:张风捷特烈<br></br>
 * 时间:2019/1/20/020:18:25<br></br>
 * 邮箱:1981462002@qq.com<br></br>
 * 说明:绿色Activity
 */
class BlueActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val view = View(this)
        view.setBackgroundColor(Color.BLUE)
        title = "BlueActivity"
        view.setOnClickListener { v ->
            startActivity(Intent(this, RedActivity::class.java))
            overridePendingTransition(R.anim.close_enter, R.anim.close_exit)
        }
        setContentView(view)
    }
    override fun onBackPressed() {
        super.onBackPressed()//右移入---右移出
                overridePendingTransition(R.anim.close_enter, R.anim.close_exit)
    }
} 

2.跳转动画
---->[open_enter.xml]----------------------
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/decelerate_interpolator">
    <!--左移入-->
    <translate
            android:duration="500"
            android:fromXDelta="100%p"
            android:toXDelta="0%p"/>
</set>

---->[open_exit.xml]----------------------
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/decelerate_interpolator">
    <!--左移出-->
    <translate
            android:duration="500"
            android:fromXDelta="0%p"
            android:toXDelta="-100%p"/>
</set>

---->[close_enter.xml----------------------
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/decelerate_interpolator">
    <!--右移入-->
    <translate
            android:duration="500"
            android:fromXDelta="-100%p"
            android:toXDelta="0%p"/>
</set>

---->[close_exit.xml]----------------------
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/decelerate_interpolator">
    <!--右移出-->
    <translate
            android:duration="500"
            android:fromXDelta="0%p"
            android:toXDelta="100%p"/>
</set> 

这样就可以了


3.另外还可以配置动画的style

用起来比在代码里方便些

<!--配置Activity进出动画-->
<style name="TranAnim_Activity" parent="@android:style/Animation.Activity">
    <item name="android:activityOpenEnterAnimation">@anim/open_enter</item>
    <item name="android:activityOpenExitAnimation">@anim/open_exit</item>
    <item name="android:activityCloseEnterAnimation">@anim/close_enter</item>
    <item name="android:activityCloseExitAnimation">@anim/close_exit</item>
</style>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/TranAnim_Activity</item>
</style> 

五、Acticity的启动源码分析

一直想总结一下Activity的启动流程(),这里从Activity的生命周期入手
本文所讲述的启动流程主要是ActivityThread的H在接收到消息之后,即handleMessage
至于消息如何传递过来的将在跨进程通信篇讲述

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3j0Xhn7g-1630918359676)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95c3ab40672?imageView2/0/w/1280/h/960/ignore-error/1)]


1.谁是幕后黑手?
翻一下源码可以看出Context只是一个抽象类,定义了很多抽象方法 
而ContextWrapper作为实现类将所有的工作甩手给了一个mBase的Context成员变量
ContextThemeWrapper寥寥百行代码,也不会是幕后黑手,现在台面上只有mBase 

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QnYu4sPV-1630918359677)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95d07838d7c?imageView2/0/w/1280/h/960/ignore-error/1)]


2.Activity是如何创建的?

相信应该没有人去new Activity(),framework 层是如何创建Activity的实例呢?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bEMlC1Vv-1630918359677)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95d1f384259?imageView2/0/w/1280/h/960/ignore-error/1)]

 ---->[ActivityThread]-------
 final H mH = new H();
 
 ---->[ActivityThread$H#handleMessage]-------
public void handleMessage(Message msg) {
 switch (msg.what) {
      case LAUNCH_ACTIVITY: {//启动Activity
          Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
          //r:记录Activity的一些描述信息
          final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
          //通过r来获取包信息
          r.packageInfo = getPackageInfoNoCheck(
                  r.activityInfo.applicationInfo, r.compatInfo);
          //开启的核心方法(划重点)
          handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
          Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

 ---->[ActivityThread#handleLaunchActivity]-------
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
    //在这里返回来Activity的对象
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        Bundle oldState = r.state;
        handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        //略...
}

 ---->[ActivityThread#performLaunchActivity]-------
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
 //略...
   ComponentName component = r.intent.getComponent();
   Activity activity = null;
   try {
       java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
       //此处可见是mInstrumentation创建的Activity
       activity = mInstrumentation.newActivity(
               cl, component.getClassName(), r.intent);
       StrictMode.incrementExpectedActivityCount(activity.getClass());
 //略...
    return activity;
    }
    
    
 ---->[Instrumentation#newActivity]-------
 public Activity newActivity(ClassLoader cl, String className,
         Intent intent)
         throws InstantiationException, IllegalAccessException,
         ClassNotFoundException {
    //通过类加载器生成Activity实例
     return (Activity)cl.loadClass(className).newInstance();
 } 

3.Application实例化及onCreate()方法调用

实现移到刚才创建Activity的performLaunchActivity方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qsagc4W1-1630918359678)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95d040a5aab?imageView2/0/w/1280/h/960/ignore-error/1)]

 ---->[ActivityThread#performLaunchActivity]-------
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
 //略...
   ComponentName component = r.intent.getComponent();
   Activity activity = null;
   try {
       java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
       activity = mInstrumentation.newActivity(
               cl, component.getClassName(), r.intent);
       StrictMode.incrementExpectedActivityCount(activity.getClass());
 //略...
    try {
    //创建Activity之后通过ActivityClientRecord的packageInfo对象的makeApplication
    //来创建Application,packageInfo是一个LoadedApk类的对象
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
//略...
    }

 ---->[LoadedApk#makeApplication]-------
public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }
        Application app = null;
//略...

        try {
            java.lang.ClassLoader cl = getClassLoader();
//略...
            //这里ContextImpl出场了
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            //这里通过mInstrumentation的newApplication方法创建Application对象
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            //将创建的Application设置到appContext上
            appContext.setOuterContext(app);
        }
        //略...
        //mActivityThread将当前app加入mAllApplications列表中
        mActivityThread.mAllApplications.add(app);
        mApplication = app;
        if (instrumentation != null) {
            try {
            //这时调用application的OnCreate方法
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!instrumentation.onException(app, e)) {
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    throw new RuntimeException(
                        "Unable to create application " + app.getClass().getName()
                        + ": " + e.toString(), e);
                }
            }
        }
        return app;
    }

 ---->[Instrumentation#newApplication]-------
public Application newApplication(ClassLoader cl, String className, Context context)
        throws InstantiationException, IllegalAccessException, 
        ClassNotFoundException {
        //也是通过反射获取Application实例
    return newApplication(cl.loadClass(className), context);
}

 ---->[Instrumentation#callApplicationOnCreate]-------
 public void callApplicationOnCreate(Application app) {
     app.onCreate();//直接调用onCreate onCreate
 } 

4.Activity的Context的创建及onCreate()方法的调用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Xo9sakDL-1630918359679)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95d2a035a70?imageView2/0/w/1280/h/960/ignore-error/1)]

 ---->[ActivityThread#performLaunchActivity]-------
 if (activity != null) {
    Context appContext = createBaseContextForActivity(r, activity);
    CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
    //Activity的一些配置信息
    Configuration config = new Configuration(mCompatConfiguration);
    if (r.overrideConfig != null) {
        config.updateFrom(r.overrideConfig);
    }
    if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
            + r.activityInfo.name + " with config " + config);
    Window window = null;
    if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
        window = r.mPendingRemoveWindow;
        r.mPendingRemoveWindow = null;
        r.mPendingRemoveWindowManager = null;
    }
    //将Activity和window绑定
    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);

    if (customIntent != null) {
        activity.mIntent = customIntent;
    }
    r.lastNonConfigurationInstances = null;
    activity.mStartedActivity = false;
    int theme = r.activityInfo.getThemeResource();
    if (theme != 0) {
        activity.setTheme(theme);
    }

    activity.mCalled = false;
    if (r.isPersistable()) {
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }


---->[ActivityThread#createBaseContextForActivity]-------
private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {
//略...
    //看这里appContext是ContextImpl类对象,Activity的Context幕后黑手出现了
    ContextImpl appContext = ContextImpl.createActivityContext(
            this, r.packageInfo, r.token, displayId, r.overrideConfig);
    appContext.setOuterContext(activity);
    Context baseContext = appContext;

    final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
    // For debugging purposes, if the activity's package name contains the value of
    // the "debug.use-second-display" system property as a substring, then show
    // its content on a secondary display if there is one.
    String pkgName = SystemProperties.get("debug.second-display.pkg");
    if (pkgName != null && !pkgName.isEmpty()
            && r.packageInfo.mPackageName.contains(pkgName)) {
        for (int id : dm.getDisplayIds()) {
            if (id != Display.DEFAULT_DISPLAY) {
                Display display =
                        dm.getCompatibleDisplay(id, appContext.getDisplayAdjustments(id));
                baseContext = appContext.createDisplayContext(display);
                break;
            }
        }
    }
    return baseContext;
}


---->[ContextImpl#createActivityContext]-------
static ContextImpl createActivityContext(ActivityThread mainThread,
        LoadedApk packageInfo, IBinder activityToken, int displayId,
        Configuration overrideConfiguration) {
    if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
    return new ContextImpl(null, mainThread, packageInfo, activityToken, null, 0,
            null, overrideConfiguration, displayId);
}

---->[Instrumentation#callActivityOnCreate]-------
public void callActivityOnCreate(Activity activity, Bundle icicle,
        PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState);
    postPerformCreate(activity);
}

---->[Activity#performCreate]-------
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        restoreHasCurrentPermissionRequest(icicle);
        onCreate(icicle, persistentState);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
    }

---->[Activity#attach]-----------------
final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window) {
    attachBaseContext(context);

    mFragments.attachHost(null /*parent*/);
    //这里的Window实现类是PhoneWindow
    mWindow = new PhoneWindow(this, window);
    mWindow.setWindowControllerCallback(this);
    mWindow.setCallback(this);
    mWindow.setOnWindowDismissedCallback(this);
    mWindow.getLayoutInflater().setPrivateFactory(this);
    if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
        mWindow.setSoftInputMode(info.softInputMode);
    }
    if (info.uiOptions != 0) {
        mWindow.setUiOptions(info.uiOptions);
    }
    mUiThread = Thread.currentThread();
    
    mMainThread = aThread;
    mInstrumentation = instr;
    mToken = token;
    mIdent = ident;
    mApplication = application;
    mIntent = intent;
    mReferrer = referrer;
    mComponent = intent.getComponent();
    mActivityInfo = info;
    mTitle = title;
    mParent = parent;
    mEmbeddedID = id;
    mLastNonConfigurationInstances = lastNonConfigurationInstances;
    if (voiceInteractor != null) {
        if (lastNonConfigurationInstances != null) {
            mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
        } else {
            mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
                    Looper.myLooper());
        }
    }

    mWindow.setWindowManager(
            (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
            mToken, mComponent.flattenToString(),
            (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
    if (mParent != null) {
        mWindow.setContainer(mParent.getWindow());
    }
    mWindowManager = mWindow.getWindowManager();
    mCurrentConfig = config;
 } 

5.Activity的布局加载

setContentView我们再熟悉不过了,看一下Activity源码是如何加载的

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SsWMKDEV-1630918359679)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95d3e06daa6?imageView2/0/w/1280/h/960/ignore-error/1)]

---->[Activity#setContentView]-----------------
public void setContentView(@LayoutRes int layoutResID) {
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}

//可见是通过Window的setContentView来加载布局的,
//通过attach方法知道这个window对象是PhoneWindow类

---->[PhoneWindow#setContentView]-----------------
 @Override
 public void setContentView(View view, ViewGroup.LayoutParams params) {
     if (mContentParent == null) {
         installDecor();//初始化DecorView
     } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
         mContentParent.removeAllViews();
     }
     if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
         view.setLayoutParams(params);
         final Scene newScene = new Scene(mContentParent, view);
         transitionTo(newScene);
     } else {
         mContentParent.addView(view, params);
     }
     mContentParent.requestApplyInsets();
     final Callback cb = getCallback();
     if (cb != null && !isDestroyed()) {
         cb.onContentChanged();
     }
 }

---->[PhoneWindow#installDecor]-----------------
 private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor();
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        }
        if (mContentParent == null) {
            //通过DecorView来创建mContentParent
            mContentParent = generateLayout(mDecor);
         //对mDecor进行处理,略...
         
---->[PhoneWindow#generateDecor]-----------------
    protected DecorView generateDecor() {
        return new DecorView(getContext(), -1);
    }

>DecorView何许人也?
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker
可见是一个帧布局FrameLayout,最顶层的视图 

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JLmA0FaG-1630918359680)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95d44fbc487?imageView2/0/w/1280/h/960/ignore-error/1)]


6.Activity的onResume和onRestart方法的回调

onCreate分析了,onResume基本是差不多,还是在H类中的
handleMessage中处理信息,当标识为RESUME_ACTIVITY时,调用handleResumeActivity

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z7Sq7NfA-1630918359680)(https://user-gold-cdn.xitu.io/2019/4/23/16a4a95d472c148f?imageView2/0/w/1280/h/960/ignore-error/1)]

---->[ActivityThread#handleMessage]-------
case RESUME_ACTIVITY:
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
    SomeArgs args = (SomeArgs) msg.obj;
    handleResumeActivity((IBinder) args.arg1, true, args.argi1 != 0, true,
            args.argi3, "RESUME_ACTIVITY");
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

---->[ActivityThread#handleResumeActivity]-------
 final void handleResumeActivity(IBinder token,
         boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
     ActivityClientRecord r = mActivities.get(token);
     if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
         return;
     }

     // If we are getting ready to gc after going to the background, well
     // we are back active so skip it.
     unscheduleGcIdler();
     mSomeActivitiesChanged = true;

     // TODO Push resumeArgs into the activity for consideration
     r = performResumeActivity(token, clearHide, reason);

---->[ActivityThread#performResumeActivity]-------
public final ActivityClientRecord performResumeActivity(IBinder token,
        boolean clearHide, String reason) {
    ActivityClientRecord r = mActivities.get(token);
            //略...
            r.activity.performResume();
            
---->[Activity#performResume]-------
final void performResume() {
    performRestart();//可见是先调用了Restart方法
    mFragments.execPendingActions();
    mLastNonConfigurationInstances = null;
    mCalled = false;
    // mResumed is set by the instrumentation
    mInstrumentation.callActivityOnResume(this);
    if (!mCalled) {

---->[Activity#performRestart]-------
final void performRestart() {
        //略...
        mInstrumentation.callActivityOnRestart(this);
//又看到老朋友mInstrumentation了,
//可以看到Activity的生命周期由mInstrumentation全权负责  
//就连调用本类的一个onRestart方法都要mInstrumentation来转手

---->[Instrumentation#callActivityOnRestart]-------
public void callActivityOnRestart(Activity activity) {
    activity.onRestart();
}

---->[Instrumentation#callActivityOnResume]-------
public void callActivityOnResume(Activity activity) {
    activity.mResumed = true;
    activity.onResume();
    
    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                am.match(activity, activity, activity.getIntent());
            }
        }
    }
}

---->[ActivityThread#handleResumeActivity]-------
//回调onResume后进行window界面显示
 if (r.window == null && !a.mFinished && willBeVisible) {
     r.window = r.activity.getWindow();
     View decor = r.window.getDecorView();
     decor.setVisibility(View.INVISIBLE);
     ViewManager wm = a.getWindowManager();
     WindowManager.LayoutParams l = r.window.getAttributes();
     a.mDecor = decor;
     l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
     l.softInputMode |= forwardBit;
     if (r.mPreserveWindow) {
         a.mWindowAdded = true;
         r.mPreserveWindow = false;
         // Normally the ViewRoot sets up callbacks with the Activity
         // in addView->ViewRootImpl#setView. If we are instead reusing
         // the decor view we have to notify the view root that the
         // callbacks may have changed.
         ViewRootImpl impl = decor.getViewRootImpl();
         if (impl != null) {
             impl.notifyChildRebuilt();
         }
     }
     if (a.mVisibleFromClient && !a.mWindowAdded) {
         a.mWindowAdded = true;
         wm.addView(decor, l);
     } 

结尾

我还总结出了互联网公司Android程序员面试涉及到的绝大部分面试题及答案,并整理做成了文档,以及系统的进阶学习视频资料,免费分享给大家。
(包括Java在Android开发中应用、APP框架知识体系、高级UI、全方位性能调优,NDK开发,音视频技术,人工智能技术,跨平台技术等技术资料),希望能帮助到你面试前的复习,且找到一个好的工作,也节省大家在网上搜索资料的时间来学习。

CodeChina开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》

eusing
// the decor view we have to notify the view root that the
// callbacks may have changed.
ViewRootImpl impl = decor.getViewRootImpl();
if (impl != null) {
impl.notifyChildRebuilt();
}
}
if (a.mVisibleFromClient && !a.mWindowAdded) {
a.mWindowAdded = true;
wm.addView(decor, l);
}


### 结尾

**我还总结出了互联网公司Android程序员面试涉及到的绝大部分面试题及答案,并整理做成了文档,以及系统的进阶学习视频资料,免费分享给大家。
(包括Java在Android开发中应用、APP框架知识体系、高级UI、全方位性能调优,NDK开发,音视频技术,人工智能技术,跨平台技术等技术资料),希望能帮助到你面试前的复习,且找到一个好的工作,也节省大家在网上搜索资料的时间来学习。**

### **[CodeChina开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》](https://codechina.csdn.net/m0_60958482/android_p7)**

![image](https://img-blog.csdnimg.cn/img_convert/025fa76aefb47e49fed7a43eac621e8c.png)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值