The code was not executed when the Android dialog was forked too fast (race status)

In my Android application, I have a dialog box with this code:

.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); doStuff(); doMorestuffThatTakesTime(); } }) 

I noticed that if I click Yes very quickly, the code in doStuff () is not executed. I wondered if dialog.cancel () had anything to do with it, but the problem exists even with the fact that it has been moved to the end and also completely removed.

It seems like some kind of race condition, but what is the problem and how do I fix it?

+4
source share
1 answer

A warning. Even more proof of conceptual code: You can try starting the stream by clicking, as in:

  builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //cancels itself? Thread thread= new Thread( new Runnable() { public void run() { try{ Thread.sleep(3000); //<== mimic time intensive task } catch(Exception e){ } Log.d(TAG,"done"); myHandler.sendEmptyMessage(0); } }); thread.setDaemon(true); thread.start(); dialog.dismiss(); } }); 

And delay the message in one operation handler:

 private Handler myHandler= new Handler(){ @Override public void handleMessage(Message msg){ switch(msg.what){ case 0: this.removeMessages(0); Log.d(TAG,"gotit"); break; default: super.handleMessage(msg); break; } } }; 

This will not work if you try to touch the user interface from a new thread.

0
source

All Articles