Here is a few bit of code:
public class ShowDialog extends Thread {
private static String mTitle="Please wait";
private static String mText="Loading...";
private Activity mActivity;
private ProgressDialog mDialog;
ShowDialog(Activity activity) {
this(activity, mTitle, mText);
}
ShowDialog(Activity activity, String title) {
this(activity, title, mText);
}
ShowDialog(Activity activity, String title, String text) {
super();
mText=text;
mTitle=title;
mActivity=activity;
if (mDialog == null) {
mDialog = new ProgressDialog(mActivity);
mDialog.setTitle(mTitle);
mDialog.setMessage(mText);
mDialog.setIndeterminate(true);
mDialog.setCancelable(true);
mDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
mDialog.dismiss();
interrupt();
}
});
}
}
public void run() {
mDialog.show();
while(!isInterrupted())
mDialog.dismiss();
mDialog=null;
}
}
And in my main activity:
ShowDialog show = new ShowDialog(this, "Please wait!","Loading badly...");
show.start();
SystemClock.sleep(2000);
show.interrupt();
I know I might use an async task and all the stuff but that is not what I want. Replace the SystemClock.sleep by anything that takes some time. The idea is to execute the code between start and interrupt in the UI thread and make a seperate thread handling the ProgressDialog.
What’s wrong with my thread ?
Thanks a lot!
To wait for a Thread to complete, you should use the
Thread.join()method. But now I see you’re not wanting to wait for it to complete, but you need to control when it completes. Still, you want to avoid interrupting threads in this fashion.In your
ShowDialogclass, add adismiss()method that you can call from yourmain, instead ofinterrupt(). Also add aboolean dismiss = falseinstance variable. Indismiss(), adddismiss = true, thennotify();. Inrun(), replace your constantwhile()loop (was running constantly, and very inefficient) withwhile(!dismiss){wait()}. You will still need to add synchronization blocks and exception handling, but this should get you off to a good start.Here is a generic-Java (non-android) simplified example:
You mentioned you didn’t want to use
AsyncTask, but I would still reconsider. (What are your reasons against it?)