在非Activity中使用startActivity:Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

96
一个会写诗的程序员
2017.05.08 16:40* 字数 156

在非Activity中使用startActivity:Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

问题描述

在APP 1中启动APP 2中的Activity。

Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri1 = Uri.parse("xxxx://xxxx/page/link?url=http%3A%2F%2Fwww.baidu.com");
                intent.setData(uri1);

           

                Context context = getApplicationContext();
                if (null != intent.resolveActivity(pm)) {
                    context.startActivity(intent);
                }

错误提示信息:

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?

原因分析

activity继承了context重载了startActivity方法,如果使用acitvity中的startActivity,不会有任何限制。

而如果直接使用context的startActivity则会报上面的错误,根据错误提示信息,可以得知,如果要使用这种方式需要打开新的TASK。

解决方法:

加上Flags

   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

  context.startActivity(intent);
Intent intent = new Intent(Intent.ACTION_VIEW);
                 Uri uri1 = Uri.parse("xxxx://xxxx/page/link?url=http%3A%2F%2Fwww.baidu.com");
                intent.setData(uri1);

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Context context = getApplicationContext();
                if (null != intent.resolveActivity(pm)) {
                    context.startActivity(intent);
                }
Android
Web note ad 1