My app is using AsyncTask using the getData method and is calling the Server and show the results inside a gridview.
I think about the top point Visit .
what happen to AsyncTask if the process waits much longer?
And how do I Control it in this Circumstance?
If it can not be controlled with AsyncTask , is there any other way(other class)?
is this new class the Same(like) these Methods ( onPost(),onPre(),doInBack(),...) ?
I personally like to have a timeout time for an AsyncTask using a Handler with postDelayed() to handle closing an AsyncTask if it takes to long and let the user know it has run for too long, or if internet connection is out.
Exmaple:
public static void performCountdown(final AsyncTask task, final Context ctx){
//If network access is not possible, cancel task.
if(!checkNetworkStatus(ctx)){
task.cancel(true);
}else {
//Run a handler thread to timeout a query if it takes too long.
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
//Task has taken longer then 15 seconds
task.cancel(true);
}
};
handler.postDelayed(runnable, 15000);
}
}
And you could call this performCountdown in your onPreExecute() for the AsyncTask. I suggest at each task.cancel(true) call using a callback or creating a Toast for the user, but I'll leave that bit up to you. Also MAKE SURE you add this to the task's onPostExecute()
handler.removeCallbacksAndMessages(null);
This will cancel the handler so that it doesn't try to cancel your task if it successfully executes.
Which requires having a reference to the handler you called in onPreExexcute(). Which you could handle by having a class that extends AsyncTask and can maintain reference / these method calls.
/**
* Check the network's state on the current device.
*/
public static boolean checkNetworkStatus(Context ctx){
ConnectivityManager manager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info == null) return false;
if(info.isRoaming()) return false;
return info != null && info.isConnected();
}