您的位置:首页 > 移动开发 > Android开发

【Android 一般进阶】不建议在Service以及BroadcastReceive startActivity

2015-03-26 14:27 375 查看
在谷歌官方的API文档中,特别建议开发者不要在Service以及BroadcastReceive startActivity,这是为了防止在用户完全不知情的情况下,突然弹出一个页面中断了他的操作。

http://developer.android.com/guide/practices/seamlessness.html#interrupt
中有如下解释:

That is, don't call startActivity() from BroadcastReceivers or Services running in the background. Doing so will interrupt whatever application is currently running, and result in an annoyed user. Perhaps even worse, your Activity may become
a "keystroke bandit" and receive some of the input the user was in the middle of providing to the previous Activity. Depending on what your application does, this could be bad news.

翻译过来的大概意思是:如果你在Service或者BroadcastReceive启动了activity,那么就会中断当前的动作,结果会惹毛用户。可能更糟糕的是,你的activity会变成输入强盗,掠夺用户的输入(用户以为是在之前的页面)。

水平有限,不知道是否翻译正确。

如果在Service startActivity,那么就会报"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_ACTIVITY_NEW_TASK flag即可。

在BroadcastReceivers 中startActivity是没有问题的,不会报错(按官方的说明应该会报错啊,这点我也不得其解。),不需要添加FLAG_ACTIVITY_NEW_TASK flag。

建议还是按官方的API来做开发吧。多谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐