这是我发送广播的代码,我在这里更改本地数据库表,然后发送广播:
for (int i = 0; i < forms.length(); i++) {
retrofit2.Call<SubmitFormResponse> call;
call = RetrofitClass.getInstance().getWebRequestsInstance().formSubmitWitoutImages(tinyDB.getString(Constants.token), bodyRequest);
call.enqueue(new Callback<SubmitFormResponse>() {
@Override
public void onResponse(Call<SubmitFormResponse> call, Response<SubmitFormResponse> response) {
if (response.isSuccessful()) {
formIds.add(formId);
QueueModel model = databaseHandler.getQueueIncidenceStateOnIncidenceID(task_id);
model.setNumSubmitted(++numSubmitted);
databaseHandler.updateQueuedIncidenceStateOnRunId(model);
// updateUI.updateUI(databaseHandler.getAllQueuedIncidences());
UploaderService.this.sendBroadcast(new Intent(BROADCAST_ACTION));
}
}
@Override
public void onFailure(Call<SubmitFormResponse> call, Throwable t) {
t.printStackTrace();
}
});
}
接收广播时,我将从更新的数据库表中获取列表,然后使用片段中的notifyDataSetChanged()重新初始化适配器。这是接收广播的代码:
@Override
public void onReceive(Context context, Intent intent) {
Log.e("CALLED", "Intent passed");
// pullToRefresh.setRefreshing(true);
if (adapter != null) {
list = databaseHandler.getAllQueuedIncidences();
if (list.size() == 0) {
tvNoPendingUploads.setVisibility(View.VISIBLE);
rvPendingUploads.setVisibility(View.GONE);
} else {
tvNoPendingUploads.setVisibility(View.GONE);
rvPendingUploads.setVisibility(View.VISIBLE);
adapter.setItems(list);
adapter.notifyDataSetChanged();
}
} else {
list = databaseHandler.getAllQueuedIncidences();
Log.e("Up", databaseHandler.getAllQueuedIncidences().size() + "");
if (list.size() == 0) {
tvNoPendingUploads.setVisibility(View.VISIBLE);
rvPendingUploads.setVisibility(View.GONE);
} else {
tvNoPendingUploads.setVisibility(View.GONE);
rvPendingUploads.setVisibility(View.VISIBLE);
adapter = new AdapterPendingUploads(list, getActivity());
rvPendingUploads.setLayoutManager(manager);
rvPendingUploads.setAdapter(adapter);
}
}
// pullToRefresh.setRefreshing(false);
}
};
接收者已在onCreateView()中注册,而未在onDestroy()中注册:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_pending_uploads, container, false);
init(view);
clickListeners();
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(
BROADCAST_ACTION));
return view;
}
@Override
public void onDestroy() {
getActivity().unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
sendBroadcast()不会立即调用BroadcastReceiver的onRecieve(),而是等待循环结束,其中sendBroadcast()被调用了n次,最后onRecieve()被调用了n-次数,连续不断。我需要在点击每个API之后更新UI。击中每个API后,应该同时调用sendBroadcast()和onRecieve()。请告诉我我在做什么错?
您可以尝试使用EventBus库。