刨根究底之Service為什么能啟動Activity

*本篇文章已授權(quán)微信公眾號 guolin_blog (郭霖)獨家發(fā)布

今天開發(fā)過程中被測試提了個bug.原來我一不注意,用Service的Context啟動Activity導致報錯(我用我自己的手機可以啟動).

java.lang.RuntimeException: Error receiving broadcast Intent { act=com....}
...
Caused by: android.util.AndroidRuntimeException: 
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

最終解決辦法就是給Intent加個FLAG_ACTIVITY_NEW_TASK的flag就能順利啟動了

intent.addFlag(Intent.FLAG_ACTIVITY_NEW_TASK);

這里先上一張圖

Activity啟動權(quán)限圖.jpg

可以看出,除了Activity以外,其他組件都是不允許去啟動Activity的.但今天用低端三星機(Android4.4)啟動報錯.而用我的P20Pro徠卡三攝(Android8.0)卻能正常啟動.這不是跟這張圖說的不一樣嗎...

那就來看看源碼是怎么寫的吧
首先看下Activity是怎么啟動的.當用Activity啟動Activity時會調(diào)用Activity.startActivity(intent)

Activity
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    //最終會調(diào)
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
            ......//省略無關(guān)代碼
        } else {
            ......//省略無關(guān)代碼
        }
    }

這里的mParent是ActivityThread.scheduleLaunchActivity()里的ActivityClientRecord傳給他的,默認為空.這里的Instrumentation.startActivity()就表示開始啟動Activity了,具體啟動流程就不在本篇里詳細說明了,之前寫過一篇縷清楚Activity啟動流程的文章,給個傳送門.這個啟動過程比較繁瑣,我是建議大家自己找個源碼一步一步跟下去會學的比較扎實.

那么其他組件啟動Activity的流程是怎樣呢?
像Service,BroadcastReceiver,Application等都是ContextWrapper的子類,調(diào)用startActivity()時會調(diào)用ContextWrapper的startActivity()

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

這個mBase就是ContextImpl.這個ContextImpl是在ActivityThread里賦值的:
Activity-->ActivityThread::performLaunchActivity()
Service-->ActivityThread::handleCreateService()
Application-->LoadedApk::makeApplication()
有興趣的同學自行查看.

那我們來看下ContextImpl的startActivity().
先看低版本的

Android4.4 api-19
ContextImpl
    @Override
    public void startActivity(Intent intent) {
        warnIfCallingFromSystemProcess();
        startActivity(intent, null);
    }

    @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);
    }

很簡單,就是非Activity的Context啟動Activity時如果不給intent設(shè)置FLAG_ACTIVITY_NEW_TASK就會報錯.
然后再來看高版本的:

Android8.0 api-27
ContextImpl
    @Override
    public void startActivity(Intent intent) {
        warnIfCallingFromSystemProcess();
        startActivity(intent, null);
    }

    @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.
        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0
                && 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);
    }

跟舊版本的代碼相比,這里多了個options的非空判斷(options != null),關(guān)鍵就在這里.
由于這里options傳的就是null,于是就跳過了這個異常.那么,這里的邏輯是"&&",有一個不成立就算失敗,那么我們不設(shè)置FLAG_ACTIVITY_NEW_TASK就能順利的啟動Activity了.
這里的注釋翻譯下是:從Activity外部(Service,BroadcastReceiver,Application等)不設(shè)置FLAG_ACTIVITY_NEW_TASK是不能啟動Activity的,除非調(diào)用者指定Activity要啟動的task的Id.
可是我也并沒有指定task的id就能成功啟動了啊,這應該算Android系統(tǒng)的一個bug吧.看來谷歌開發(fā)人員也有犯渾的時候.

這段代碼我查了下是Android7.0(api24)開始有的,也就是說Android6.0或以下系統(tǒng)還是不能啟動的,我測試了下確實是這樣.
以下是Android7.0的測試:


啟動Activity的service.gif

以下是Android6.0的測試:


6.0啟動Activity的service.gif

邏輯就是MainActivity點擊按鈕啟動TService,然后TService啟動SubActivity

MainActivity:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void startService(View view) {
        startService(new Intent(this, TService.class));
    }

TService:
    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent(this, SubActivity.class);
        intent.putExtra("data","從Service啟動的Activity");
        startActivity(intent);
    }

SubActivity:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
        TextView textView = findViewById(R.id.tv);
        String data = getIntent().getStringExtra("data");
        textView.setText(data);
    }

我們最終得出結(jié)論Android7.0和Android8.0里Service,BroadcastReceiver,Application等都是可以啟動Activity的.
------------------2018.11.1--------------------
今天我又看了下Android9.0的源碼,貌似已經(jīng)修復了這個bug

ContextImpl
    @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);
    }

這里已經(jīng)改為&&options == null了.應該已經(jīng)修復了.我目前沒有測試的條件,有興趣的同學可以去測試一下,Android9.0中Service已經(jīng)不能直接啟動Activity了.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容