与广播接收器更新主动活动UI [英] Update active Activity UI with BroadcastReceiver

查看:185
本文介绍了与广播接收器更新主动活动UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现用下面的例如

然而,一旦报警熄灭/是收到我想更新我的的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 扩展广播接收器)类

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆