1.在Activity中跳轉到其餘的Activity時,兩種使用方法是同樣的:java
this.startActivity(intent); context.startActivity(intent); 複製代碼
2.從非 Activity (例如從其餘Context中)啓動Activity則必須給intent設置Flag:FLAG_ACTIVITY_NEW_TASK:android
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ; mContext.startActivity(intent); 複製代碼
首先看下Activity和context的繼承關係:app
要知道Activity和context中的StartActivity有什麼區別,咱們看下它們分別是怎麼實現startActivity函數的:ide
1.Context是抽象類,它的startActivity函數是抽象方法:
函數
public abstract void startActivity(@RequiresPermission Intent intent); 複製代碼
2.ContextWrapper類只是調用了Context的實現:
ui
@Override public void startActivity(Intent intent) { mBase.startActivity(intent); } 複製代碼
3.ContextThemeWrapper中沒有實現此方法
this
4.Activity中:
spa
@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自身的方法,因此是同樣的。code
然而在其餘的Context子類,例如ContextImpl.java中的實現,會檢查有沒有設置Flag:FLAG_ACTIVITY_NEW_TASK,不然會報錯:blog
@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); } 複製代碼
這也就是爲何Activity的startActivity和Context的startActivity會有上面那些使用上的不一樣的緣由了。