Update active Activity UI with BroadcastReceiver

2019-08-16 02:01发布

问题:

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