在BroadcastReceiver中启动Activity的问题
2014-12-03 22:30
337 查看
/** * Demo描述: * 在BroadcastReceiver中启动Activity的问题 * * 如果在BroadcastReceiver的onReceive()方法中如下启动一个Activity * Intent intent=new Intent(context,AnotherActivity.class); * context.startActivity(intent); * 可捕获异常信息: * 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()方法时 * 需要给Intent设置一个flag:FLAG_ACTIVITY_NEW_TASK * * 所以在BroadcastReceiver的onReceive()方法中启动Activity应写为: * Intent intent=new Intent(context,AnotherActivity.class); * intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); * context.startActivity(intent); * * * 之前描述了问题的现象和解决办法,现在试着解释一下原因: * 1 在普通情况下,必须要有前一个Activity的Context,才能启动后一个Activity * 2 但是在BroadcastReceiver里面是没有Activity的Context的 * 3 对于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. * * 4 其实该flag和设置Activity的LaunchMode为SingleTask的效果是一样的 * * * 如有更加深入的理解,请指点,多谢 * */
相关文章推荐
- 在BroadcastReceiver中启动Activity的问题
- 在BroadcastReceiver中启动Activity的问题
- Android初学习 - 在BroadcastReceiver中启动Activity的问题
- 关于在BroadcastReceiver中启动Activity的问题
- 安卓隐式Intent启动Activity和BroadcastReceiver若干注意点
- 从BroadcastReceiver或者Service当中启动Activity
- Android Service BroadcastReceiver 合用 应用全局随便启动activity
- Android -- BroadcastReceiver 中启动Activity
- 从BroadcastReceiver中启动activity
- 在BroadcastReceiver中启动Activity:
- 在BroadcastReceiver中启动Activity
- activity BroadcastReceiver Service 三大组件的启动或触发
- Android6.0以后,在BroadcastReceiver中启动AlertDialog导致程序停止运行的问题及解决办法
- 关于Android的BroadcastReceiver的onReceive方法中回调结果给Activity的问题
- BroadcastReceiver应用详解以及Android实现点击通知栏后,先启动应用再打开目标Activity
- Android 如何在service和BroadCastReceiver中 启动activity和alertdialog?
- 在BroadcastReceiver中启动Activity,需为Intent添加Flag:Intent.FLAG_ACTIVITY_NEW_TASK
- BroadcastReceiver中启动Activity
- 在service和BroadCastReceiver中 启动activity和alertdialog
- android am 启动activity service or broadcast及参数传递