I have a thread that run several operations once and I would like to stop it when the user cancels the ProgressDialog
.
public void run() {
//operation 1
//operation 2
//operation 3
//operation 4
}
This thread runs only once, so I can't implement a loop to check if he thread should still be running.
Here is my ProgressDialog :
//Wait dialog
m_dlgWaiting = ProgressDialog.show(m_ctxContext,
m_ctxContext.getText(R.string.app_name),
m_ctxContext.getText(R.string.msg_dlg_analyse_pic),
true, //indeterminate
true,
new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
m_bRunning = false;
}
});
As I don't know how to stop the thread, would it be correct to sequence the thread's operations through a loop to see if it should still be running, or is there a better way ?
public void run() {
int op = 0;
while(m_bRunning) {
switch(op) {
case 0 :
//operation 1
break;
case 1 :
//operation 2
break;
case 2 :
//operation 3
break;
case 3 :
//operation 4
break;
}
op++;
}
}
Even with this solution, if there are too much operations in the thread, it could be hard to sequence the operations. Is there a better way to achieve this ?
Use callbacks or AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog;
@Override
protected void onPreExecute()
{
this.dialog = new ProgressDialog(context);
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(true);
this.dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
@Override
public void onCancel(DialogInterface dialog)
{
// cancel AsyncTask
cancel(false);
}
});
this.dialog.show();
}
@Override
protected Void doInBackground(Void... params)
{
// do your stuff
return null;
}
@Override
protected void onPostExecute(Void result)
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}
@Override
protected void onCancelled()
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}
};
task.execute();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With