美文网首页
BroadCastReceiver开启Activity

BroadCastReceiver开启Activity

作者: 孙大硕 | 来源:发表于2019-03-12 21:21 被阅读0次

BroadCastReceiver的onRecevie()方法是在主线程中运行的,而且是有上下文环境的,所以我觉得直接启动一个Activity应该没问题,可是实际是有问题的。

在startActivity方法的注释中有这样一句话:

Note that if this method is being called from outside of an
{@link android.app.Activity} Context, then the Intent must include
the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag. This is because,
without being started from an existing Activity, there is no existing
task in which to place the new activity and thus it needs to be placed
in its own separate task.
说白了就是如果不加这个flag就没有一个Task来存放新启动的Activity.

所以我们的代码要这样写才没有问题:

Intent intent=new Intent(context,AnotherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

Context种类及其应用范围

Context的种类及其应用范围

相关文章

网友评论

      本文标题:BroadCastReceiver开启Activity

      本文链接:https://www.haomeiwen.com/subject/rteopqtx.html