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

在谷歌官方的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来做开发吧。多谢。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值