最近在制作桌面时钟应用的过程中,发现如果在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:
(2) http://developer.android.com/resources/articles/avoiding-memory-leaks.html
除此以外,还有一点令我很困惑: 究竟为何不能直接在XML中注册?