刨根究底之Service为什么能启动Activity

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c10WTiybQ1Ye3/article/details/83805188

640?wx_fmt=png


今日科技快讯


近日,FF在一份声明中表示,“在努力保留员工和供应商合作关系的同时,我们目前正在跟不同背景的全球多家投资方进一步谈判。”与恒大关系破裂后,FF陷入现金流困难,不得不采取裁员、降薪等多种方式自救,并宣布今年5月1日之后加盟FF的员工大部分将会在11月和12月停薪留职,仅留下500位左右员工继续留在公司推进FF 91 量产交付工作。


作者简介


本篇来自十蛋斯坦的投稿,分享了关于刨根究底之Service为什么能启动Activity的相关内容,一起来看看!希望大家喜欢。

十蛋斯坦的博客地址:

https://www.jianshu.com/u/7b0fa1dbf195


正文


今天开发过程中被测试提了个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);

这里先上一张图

640?wx_fmt=other

可以看出,除了Activity以外,其他组件都是不允许去启动Activity的.但今天用低端三星机(Android4.4)启动报错.而用我的P20Pro徕卡三摄(Android8.0)却能正常启动.这不是跟这张图说的不一样吗...

那就来看看源码是怎么写的吧

首先看下Activity是怎么启动的.当用Activity启动Activity时会调用Activity.startActivity(intent)

Activity
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    //最终会调
    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);
            ......//省略无关代码
        } else {
            ......//省略无关代码
        }
    }

这里的mParent是ActivityThread.scheduleLaunchActivity()里的ActivityClientRecord传给他的,默认为空.这里的Instrumentation.startActivity()就表示开始启动Activity了,具体启动流程就不在本篇里详细说明了,之前写过一篇缕清楚Activity启动流程的文章,给个传送门.

https://www.jianshu.com/p/3d704b60860e

这个启动过程比较繁琐,我是建议大家自己找个源码一步一步跟下去会学的比较扎实.

那么其他组件启动Activity的流程是怎样呢?

像Service,BroadcastReceiver,Application等都是ContextWrapper的子类,调用startActivity()时会调用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设置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),关键就在这里.
由于这里options传的就是null,于是就跳过了这个异常.那么,这里的逻辑是"&&",有一个不成立就算失败,那么我们不设置FLAG_ACTIVITY_NEW_TASK就能顺利的启动Activity了.
这里的注释翻译下是:从Activity外部(Service,BroadcastReceiver,Application等)不设置FLAG_ACTIVITY_NEW_TASK是不能启动Activity的,除非调用者指定Activity要启动的task的Id.

可是我也并没有指定task的id就能成功启动了啊,这应该算Android系统的一个bug吧.看来谷歌开发人员也有犯浑的时候.

这段代码我查了下是Android7.0(api24)开始有的,也就是说Android6.0或以下系统还是不能启动的,我测试了下确实是这样.

以下是Android7.0的测试:

640?wx_fmt=gif

以下是Android6.0的测试:

640?wx_fmt=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);
    }

我们最终得出结论Android7.0和Android8.0里Service,BroadcastReceiver,Application等都是可以启动Activity的.

------------------2018.11.1--------------------

今天我又看了下Android9.0的源码,貌似已经修复了这个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);
    }

这里已经改为&&options == null了.应该已经修复了.我目前没有测试的条件,有兴趣的同学可以去测试一下,Android9.0中Service已经不能直接启动Activity了.


欢迎长按下图 -> 识别图中二维码

或者 扫一扫 关注我的公众号

640.png?

640?wx_fmt=jpeg

猜你喜欢

转载自blog.csdn.net/c10WTiybQ1Ye3/article/details/83805188