Android, AsyncTask, check status?
getStatus()
checks whether the the AsyncTask
is pending, running, or finished.
LoadMusicInBackground lmib = new LoadMusicInBackground();
if(lmib.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(lmib.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(lmib.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
}
If you want to check if your action actually succeeded (i.e. the music was successfully loaded), then you need to come up with your own method that determines that. The getStatus()
can only determine the state of the actual thread in AsyncTask
.
This is asynchronous programing - you should not check from UI thread, because this means that you are blocking the UI thread ( presumably running check in loop with Thread.sleep()?).
Instead you should be called when AsyncTask is done: from it's onPostExecute()
call whatever method in Activity you need.
Caveat: the downside of this approach is that Activity must be active when background thread finishes. This is often not the case, for example if back is prwssed or orientation is changed. Better approach is to send a broadcast from onPostExecute()
and then interested activities can register to receive it. Best part is that Activity only receives broadcast if it's active at that time, meaning that multiple Activities can register, but only the active one will receive it.
Create asynctask with listener
class ClearSpTask extends AsyncTask<Void, Void, Void> {
public interface AsynResponse {
void processFinish(Boolean output);
}
AsynResponse asynResponse = null;
public ClearSpTask(AsynResponse asynResponse) {
this.asynResponse = asynResponse;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog();
}
@Override
protected Void doInBackground(Void... voids) {
cleardata();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
hideProgressDialog();
asynResponse.processFinish(true);
}
}
And use the Asynctask
new ClearSpTask(new ClearSpTask.AsynResponse() {
@Override
public void processFinish(Boolean output) {
// you can go here
}
}).execute();
I hope this might help some people