Calling startActivity() from outside of an Activity 异常处理

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity
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?

遇到这个异常的处理是在intent里增加一个flag
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

原因:
在Context里有一个startActivity方法,Activity是继承自Context的所以在Activity里直接调用startActivity方法不会有问题,但是如果要使用Context的startActivity的方法的话(比如在service里使用context.startActivity())就需要另开一个新的task。

源码:

/**
 * 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.  

//译:这是因为没有从一个存在的activity启动,当前没有任务栈来存放新的activity,所以需要一个新的任务栈来存放你要启动的新的activity。它需要放在它自己的task里。
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.
*
*

This method throws {@link ActivityNotFoundException}
* if there was no Activity found to run the given Intent.
*
* @param intent The description of the activity to start.
*
* @throws ActivityNotFoundException
*
* @see PackageManager#resolveActivity
*/
public abstract void startActivity(Intent intent);

这就是为什么在使用Context的startActivity方法的时候(比如在Service中或者BroadcastReceiver中启动Activity)要添加一个flag:FLAG_ACTIVITY_NEW_TASK。

你可能感兴趣的:(异常处理)