我通过以下方式在我的活动中定义了一个 BroadcastReceiver,以从另一个线程上运行的 IntentService 获取结果:
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isSyncCompleted = intent.getBooleanExtra("issynccompleted", false);
if (isSyncCompleted){
showAlert("Sync completed in service");
}
context.unregisterReceiver(receiver);
}
};
//register receiver for service
registerReceiver(receiver, new IntentFilter(ContentSyncService.SERVICE_INTENT_FILTER));
请注意,我在 onReceive 代码块中注销我的接收器,而不是在 onPause 中。那是因为即使活动已被破坏,我也想让接收者监听。
但我不断收到错误消息:“ Activity ... 已泄露 IntentReceiver ... 最初在此处注册。您是否错过了对 unregisterReceiver() 的调用? ”