Is it possible to block the UI thread when displaying an alert dialog
I have this method, which basically waits for the items in the singleton queue to become empty, there is a running background service that stops once it deletes all the items in the queue and processes them one by one. This code runs in the main thread, what happens if I call wait here? Does the alert dialog still appear and prevent the user from performing any other action?
void waitForService() {
openConnectionToUploadQueue();
if(answersQueue.getCount(objInterviewQuestion.getQid()) <= 0){
answersQueue.close();
return;
}
if(!answersQueue.isInterviewUploadServiceRunning()) {
answersQueue.startInterviewUploadService();
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.auto_submit_alert_title));
builder.setCancelable(false);
builder.setMessage(R.string.uploading_pending_answers);
AlertDialog waitForServiceDialog = builder.create();
waitForServiceDialog.show();
while (answersQueue.getCount(objInterviewQuestion.getQid()) > 0) {
do nothing and keep loop running till answersQueue is empty
}
waitForServiceDialog.dismiss();
}
Solution
You should never block the UI thread. When you hold the UI thread for too long, a dialog box appears that says XXX is not responding
and asks the user to terminate your application.
Instead, you
should use callback-style calls, and when the service starts, you receive a method call from the callback to close the dialog box.
Edit:
As mentioned earlier, you need to implement BroadcastReceiver
This is a demo project that you can use as an example of how to create and use BroadcastReceiver
.