一、 首先Context启动activity可以使用Activity, Service,Receiver, Application;

首先看下Context类结构图:

startActivity()。在M和N O平台的使用

1, Activity启动不会报以下错:

ERR:android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

原因:Activity重写了StartActivity方法,在启动的时候没有做限制(具体可以查看下activity的源码);

2, 其他Context:(会报上面的错误)

其他Context都使用了ContextImp.java中的startActivity(...);

M平台会出错:

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

    }


N平台不会出错:

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

    }

以上就是M和N O 平台的区别。也是在不同平台会报错的原因。

具体activity的启动流程这里不做分析,有兴趣的可以百度下,有好多;









相关文章:

  • 2022-12-23
  • 2021-04-27
  • 2021-11-15
  • 2021-10-25
  • 2021-07-22
  • 2022-12-23
  • 2022-01-22
猜你喜欢
  • 2021-08-26
  • 2022-01-16
  • 2022-12-23
  • 2022-01-03
  • 2022-12-23
  • 2021-10-13
  • 2021-09-28
相关资源
相似解决方案