Android中Activity的startActivity和Context的startActivity有什麼不同

原文: http://tryenough.com/android-startActivity

在使用中的不同

1.在Activity中跳轉到其他的Activity時,兩種使用方法是一樣的:

this.startActivity(intent);
context.startActivity(intent);

2.從非 Activity (例如從其他Context中)啓動Activity則必須給intent設置Flag:FLAG_ACTIVITY_NEW_TASK:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ; 
mContext.startActivity(intent);

探究一下爲什麼會有這方面的差異


原文: http://tryenough.com/android-startActivity

首先看下Activity和context的繼承關係:

要知道Activity和context中的StartActivity有什麼區別,我們看下它們分別是怎麼實現startActivity函數的:

原文: http://tryenough.com/android-startActivity

1.Context是抽象類,它的startActivity函數是抽象方法:

public abstract void startActivity(@RequiresPermission Intent intent);

2.ContextWrapper類只是調用了Context的實現:

@Override
public void startActivity(Intent intent) {
    mBase.startActivity(intent);
}

3.ContextThemeWrapper中沒有實現此方法

4.Activity中:

@Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }

由此可見,在Activity中無論是使用哪一種startActivity方法都會調用到Activity自身的方法,所以是一樣的。

原文: http://tryenough.com/android-startActivity

然而在其他的Context子類,例如ContextImpl.java中的實現,會檢查有沒有設置Flag:FLAG_ACTIVITY_NEW_TASK,否則會報錯:

@Override
    public void startActivity(Intent intent, Bundle options) {
        warnIfCallingFromSystemProcess();

        // Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
        // generally not allowed, except if the caller specifies the task id the activity should
        // be launched in. A bug was existed between N and O-MR1 which allowed this to work. We
        // maintain this for backwards compatibility.
        final int targetSdkVersion = getApplicationInfo().targetSdkVersion;

        if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
                && (targetSdkVersion < Build.VERSION_CODES.N
                        || targetSdkVersion >= Build.VERSION_CODES.P)
                && (options == null
                        || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
            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);
    }

原文: http://tryenough.com/android-startActivity

這也就是爲什麼Activity的startActivity和Context的startActivity會有上面那些使用上的不同的原因了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章