Update active Activity UI with BroadcastReceiver

白昼怎懂夜的黑 提交于 2019-12-12 00:59:56

问题


I have implemented recurring alarms using the following example

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.

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


回答1:


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.

Example:

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);
}

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);
}

Initialization of your AlarmReceiver will look the following way:

updateReceiver=new AlarmReceiver(new AlarmReceiverCallback() {
    @Override
    public void onAlarmReceived(Intent intent) {
        //your list update code here
    }     
});


来源:https://stackoverflow.com/questions/14364632/update-active-activity-ui-with-broadcastreceiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!