Issue
I looked for the answers here on SO, but could not find what I need. Here is the scenario that I am working on: I have an AsyncTask that makes a web service call:
class getDataDetailTask extends AsyncTask<String, Void, DataDetail> {
@Override
protected DataDetail doInBackground(String... args) {
return AppUtils.getDataDetails();
}
@Override
protected void onCancelled(OutageDetail result) {
.... // something goes here
}
}
So let's say that the webservice call usually will timeout after 30 seconds if unsuccessful. Now, I don't want user to wait 30 seconds to find out the call has timed out, I want for it to take no more than 10 seconds. So I created a timer to look after AsyncTask:
class checkDataTask implements Runnable {
getDataDetailTask dataAsyncTask;
Context context;
public checkDataTask(getDataDetailTask asyncTask) {
dataAsyncTask = asyncTask;
}
@Override
public void run() {
mHandler.postDelayed(runnable, 10);
}
Handler mHandler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (dataAsyncTask.getStatus() == Status.RUNNING
|| dataAsyncTask.getStatus() == Status.PENDING) {
dataAsyncTask.cancel(true);
}
}
};
}
all of this calls are being setup in the onCreate method in Activity like so:
getDataDetailTask dataTask = new getDataDetailTask();
dataTask.execute();
checkDataTask check = new checkDataTask(dataTask);
(new Thread(check)).start();
when AsyncTask issues cancel(true) method, onCancelled(Object) or [onCancelled() for earlier SDK versions is being called). My question is, what should i do in my onCancelled call to "kill" the task?
Solution
Just need to setup handler that will cancel the AsyncTask
after given period of time:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run() {
if ( check.getStatus() == AsyncTask.Status.RUNNING )
check.cancel(true);
}
}, 10000 );
Answered By - mike.tihonchik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.