与广播接收器更新主动活动UI [英] Update active Activity UI with BroadcastReceiver
问题描述
我已经实现用下面的例如复发报警一>
然而,一旦报警熄灭/是收到我想更新我的的ListView
在活跃的活动。我只是有一个 ListView的一个活动
。
However, once an alarm "goes off"/is recieved I want to update my ListView
in the active Activity. I only have one activity with a ListView
.
我如何执行一次收到的主要活动课我更新UI的方法报警?如何从的onReceive()
在 AlarmReceiver
(扩展广播接收器$调用此C $ C>)类
How do I execute my update UI method in the main activity class once an alarm is received? How do you call this from onReceive()
in the AlarmReceiver
(extends BroadcastReceiver
) class
推荐答案
最简单的方法是使你的AlarmReceiver一个内部类的活动。这种方式,将可以访问所有字段和您的活性的方法。如果你不使用任何其他地方,它也可能是匿名的。
为了使更新您的活动,只有当它是积极的,注册在 onResume)接收器(
和的onPause注销其()
。注意的IntentFilter
指定动作的意图你的广播接收器
将响应。
The easiest way is to make your AlarmReceiver an inner class of your activity. This way it will have access to all fields and methods of your activity. If you don't use it anywhere else, it might as well be anonymous.
To make it update your activity only when it's active, register your receiver in onResume()
and unregister it in onPause()
. Notice the IntentFilter
specifying intent actions your BroadcastReceiver
will respond to.
例如:
private BroadcastReceiver updateReceiver;
//...
@Override
protected void onResume() {
super.onResume();
updateReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//your list update code here
}
};
IntentFilter updateIntentFilter=new IntentFilter("update");
registerReceiver(updateReceiver, updateIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
if (this.updateReceiver!=null)
unregisterReceiver(updateReceiver);
}
如果您仍然希望你AlarmReceiver成为一个单独的类,在初始化过程中通过某种回调到它:
If you still want your AlarmReceiver to be a separate class, pass some kind of callback to it during initialization:
public interface AlarmReceiverCallback {
public void onAlarmReceived(Intent intent);
}
//in your AlarmReceiver class:
private AlarmReceiverCallback callback;
public AlarmReceiver(AlarmReceiverCallback callback) {
this.callback=callback;
}
@Override
public void onReceive(Context context, Intent intent) {
callback.onAlarmReceived(intent);
}
初始化你的 AlarmReceiver
看起来下列方式:
updateReceiver=new AlarmReceiver(new AlarmReceiverCallback() {
@Override
public void onAlarmReceived(Intent intent) {
//your list update code here
}
});
这篇关于与广播接收器更新主动活动UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!