使用BroadcastReceiver更新活动的Activity UI

时间:2013-01-16 17:52:48

标签: android android-intent android-broadcast

我使用以下example

实施了定期发出的警报

然而,一旦警报“响起”/收到警报,我想更新活动活动中的ListView。我只有一项活动ListView

收到警报后,如何在主活动类中执行更新UI方法?您如何在onReceive()AlarmReceiver)班级中extends BroadcastReceiver拨打此邮件

1 个答案:

答案 0 :(得分:9)

最简单的方法是让您的AlarmReceiver成为您活动的内部类。这样,它就可以访问您活动的所有字段和方法。如果你不在其他任何地方使用它,它也可能是匿名的。 要使其仅在活动时更新您的活动,请在onResume()中注册您的接收者,并在onPause()中取消注册。请注意IntentFilter指定您BroadcastReceiver将要回复的意图操作。{/ p>

示例:

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成为一个单独的类,请在初始化期间将某种回调传递给它:

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