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

简介: 在非Activity中使用startActivity:Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag问题描述在APP 1中启动APP 2中的Activity。

在非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);
                }
相关文章
|
Java
Preference跳转activity出错Unable to find explicit activity class
使用Preference可以非常方便的实现类似设置页面这样的菜单布局,甚至可以不需写java代码。那么可以在Preference中直接添加页面跳转么?其实非常简单,在Preference添加intent标签即可
473 0
|
Java Android开发
Fragment not attached to Activity 异常
Fragment not attached to Activity 异常
Dialog显示引起的问题 Activity has leaked window DecorView@5704632[] that was originally added here
Dialog显示引起的问题 Activity has leaked window DecorView@5704632[] that was originally added here
Fragment Or DialogFragment Can not perform this action after onSaveInstanceState
转载自Fragment Or DialogFragment Can not perform this action after onSaveInstanceState 表现 可会造成app崩溃掉,具体日志如下: 异常如下: java.
2662 0
Activity finish 后 onDestroy ()并不会立马执行
只看标题就好 所以两个Activity在用到生命周期的时候,不要再onDestroy中做,控制不了
1002 0