I have recently experimented with creating an easy way to open a ProgressDialog up in a second thread, so if the main thread freezes the dialog will keep working.
Here is the class: public class ProgressDialogThread extends Thread { public Looper ThreadLooper; public Handler mHandler;
public ProgressDialog ThreadDialog; public Context DialogContext; public String DialogTitle; public String DialogMessage;
public ProgressDialogThread(Context mContext, String mTitle, String mMessage)
{
DialogContext = mContext;
DialogTitle = mTitle;
DialogMessage = mMessage;
}
public void run()
{
Looper.prepare();
ThreadLooper = Looper.myLooper();
ThreadDialog = new ProgressDialog(DialogContext);
ThreadDialog.setTitle(DialogTitle);
ThreadDialog.setMessage(DialogMessage);
ThreadDialog.show();
mHandler = new Handler();
Looper.loop();
}
public void Update(final String mTitle, final String mMessage)
{
while(mHandler == null)
synchronized(this) {
try { wait(10); }
catch (InterruptedException e) {
Log.d("Exception(ProgressDialogThread.Update)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
}
}
mHandler.post(new Runnable(){
@Override
public void run() {
ThreadDialog.setTitle(mTitle);
ThreadDialog.setMessage(mMessage);
}});
}
public void Dismiss()
{
while(ThreadDialog == null || mHandler == null)
synchronized(this) {
try { wait(10); }
catch (InterruptedException e) {
Log.d("Exception(ProgressDialogThread.Dismiss)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
}
}
mHandler.post(new Runnable(){
@Override
public void run() {
ThreadDialog.dismiss();
}});
}
public void Continue()
{
while(ThreadLooper == null || mHandler == null)
synchronized(this) {
try { wait(10); }
catch (InterruptedException e) {
Log.d("Exception(ProgressDialogThread.Continue)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
}
}
mHandler.post(new Runnable(){
@Override
public void run() {
ThreadLooper.quit();
}});
}
However it sometimes work perfectly but other times the application simply freezes and crashes eventually.
Here is an example of use:
ProgressDialogThread thread = new ProgressDialogThread(this, "Loading", "Please wait...");
thread.start();
// Do Stuff
thread.Dismiss();
thread.Continue();
It generates a lot of warning and even some crashes sometimes:
eg. Handler: Sending message to dead thread....
and exceptions like ANR in ...... Reason: keyDispatchingTimedOut
Thanks for any help, Alex.