Android在BroadcastReceiver中打开其他Activity报错解决方法
- by chenxue4076
- 11 years ago
在使用内部类 BroadcastReceiver 中使用Intent调用startActivity时报异常解决方案。 核心代码
public void onReceive(Context context, Intent intent) {
Intent mainIntent = new Intent();
mainIntent.setClass(context, MainActivity.class);
context.startActivity(mainIntent);
}
异常信息:E/AndroidRuntime(5189): java.lang.RuntimeException: Error receiving broadcast Intent { act=xxx (has extras) } in xxxxxx 可以在 E/AndroidRuntime(5189): FATAL EXCEPTION: main 上面看到一行 Warning : W/dalvikvm(5189): threadid=1: thread exiting with uncaught exception 既然是异常 exception 于是尝试在调用activity的时候添加 try 核心代码
public void onReceive(Context context, Intent intent) {
try{
Intent mainIntent = new Intent();
mainIntent.setClass(context, MainActivity.class);
context.startActivity(mainIntent);
}catch(Exception e){
e.printStackTrace();
}
}
在用LogCat看捕获到的异常 发现 System.err 错误 信息是 W/System.err(4555): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? 发现这个Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. 这个错误于是在startActivity之前添加了一行代码 mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
现在代码如下:
public void onReceive(Context context, Intent intent) {
try{
Intent mainIntent = new Intent();
mainIntent.setClass(context, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainIntent);
}catch(Exception e){
e.printStackTrace();
}
}
OK,上面的问题“Error receiving broadcast Intent” 和 “Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.”都解决了。 下面解释了为什么使用Context的startActivity方法(比如在Service中或者BroadcastReceiver中启动Activity)为什么需要添加flag:FLAG_ACTIVITY_NEW_TASK。
/**
* Launch a new activity. You will not receive any information about when
* the activity exits.
*
* 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.
*
* 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
**/
(7688)