Android OS

Is this really what you want?

2020-04-09  本文已影响0人  古风子

A组提供了一个定制的Actvity给客户组的研发调用,调用定制后的Activity的startActivity后,抛出以下异常:

2020-04-08 16:36:18.820 12184-12488...
startClient exception:  
android.util.AndroidRuntimeException  Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
        at  android.app.ContextImpl.startActivity(ContextImpl.java:916)
        at  android.content.ContextWrapper.startActivity(ContextWrapper.java:406)
        at  selfDefineActivity.startActivity(CounterfeitActivity.java:80)
         ...
        at  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at  java.lang.Thread.run(Thread.java:764)

系统报错位置

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

如上所说义,如果你通过Context调用StartActivity,则最总会调用ContextImpl的startActivity方法,并在方法内部进行检查,只有StartActivity没有设置FLAG_ACTIVITY_NEW_TAS,且系统版本是7,8,并且options 为空或者启动的taskid为-1是,才会触发抛出异常

我们遇到的问题是因为我们自定义的selfDefineActivity,重新了startActivity方法,在覆写的startActivity中通过context启动了另外一个Activity,且启动的时候Intent没有设置对应的FLAG_ACTIVITY_NEW_TAS,options,且系统版本为Android 8

解决方法:
Intent设置FLAG_ACTIVITY_NEW_TAS,或者传一个options对象即可

上一篇下一篇

猜你喜欢

热点阅读