美文网首页
Context.startActivity无法启动Activit

Context.startActivity无法启动Activit

作者: 静水红阳 | 来源:发表于2019-11-22 11:04 被阅读0次

问题描述

采用Application.startActivity()偶现无法启动Activity的现象。

原因分析

首先查询Context.javastartActivity()方法的描述,部分内容如下:

    /**
     * Launch a new activity.  You will not receive any information about when
     * the activity exits.
     *
     * <p>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.
     *
     * <p>This method throws {@link ActivityNotFoundException}
     * if there was no Activity found to run the given Intent.
     *

从以上描述可以看出,如果调用startActivity()方法的Context不是Activity的话,Intent必须要包含FLAGIntent.FLAG_ACTIVITY_NEW_TASK,原因是因为没有Activity启动Activity时可能不存在Activity栈,所以需要添加Intent属性来创建一个Activity栈。

解决办法

为启动的Intent设置intent.flags即可解决此问题。

intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

相关文章

网友评论

      本文标题:Context.startActivity无法启动Activit

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