Application Context 和 Widget Context 的区别

最近在制作桌面时钟应用的过程中,发现如果在AndroidManifest.xml中注册的<receiver>中添加

<intent-filter>
    <action android:name="android.intent.action.TIME_TICK"/>
    <action android:name="android.intent.action.TIME_SET"/>
    <action android:name="android.intent.action.TIMEZONE_CHANGED"/>
</intent-filter>
是无效的。即在继承自AppWidgetProvider的类中onReceive方法无法正常接收到ACTION_TIME_TICK系统消息。

查看了API之后发现有这么一段话:

You can not receive this through components declared in manifests, only by exlicitly registering for it with Context.registerReceiver().

因此删去了XML中的配置,改为在AppWidgetProvider继承类的onEnable方法中添加如下代码:

context.registerReceiver(this, new IntentFilter(Intent.ACTION_TIME_TICK));
context.registerReceiver(this, new IntentFilter(Intent.ACTION_TIME_CHANGED));
context.registerReceiver(this, new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED));
其中的context为onEnable(Context context)的形参。

运行后报错:

android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents 

查阅资料,在stackoverflow上找到解决方案:【http://stackoverflow.com/questions/5112529/register-broadcastreceiver-to-widget-difference-of-context-object

将context改为Context app_ctx = context.getApplicationContext();

然后再用 app_ctx 去注册Receiver,问题的确解决了。

But i still concern two questions:

Question❶: The difference between Widget Context and Application Context and other Context object (Activity Context)'

Question❷: Because context object was use usually so when to use Application context and when to use other Context.

For ❷ i had found explain relate with memory leak (Ref. 2), but i think it may not enough (Ref.2)

So if your have answer please let me known, any answer appreciated.

Thanks

★Referecens:

(1) http://groups.google.com/group/android-developers/browse_thread/thread/790da1a655f4a227/0b8d6aad1dc2d371?hl=en&lnk=gst&q=Broadcast+Receiver+From+Widget#0b8d6aad1dc2d371

(2) http://developer.android.com/resources/articles/avoiding-memory-leaks.html

除此以外,还有一点令我很困惑: 究竟为何不能直接在XML中注册?



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值