如果服务器正忙,AsyncTask class 发生了什么?

If the server is busy what happened to AsyncTask class?

我的应用程序使用 AsyncTask 和 getData 方法调用服务器并在 gridview 中显示结果。
我想到了最高点 Visit 。

如果进程等待更长时间,AsyncTask 会怎样?
在这种情况下我该如何控制它?
如果不能用 AsyncTask 控制,有没有其他办法(other class)?
这个新的 class 是否与这些方法相同(如)(onPost()、onPre()、doInBack()、...)?

我个人喜欢使用 Handler with postDelayed() 为 AsyncTask 设置一个超时时间来处理关闭 AsyncTask 如果它需要很长时间并让用户知道它有 运行 太长时间,或者如果互联网连接中断。

示例:

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);
    }
}

并且您可以在您的 onPreExecute() 中为 AsyncTask 调用此 performCountdown。我建议在每次 task.cancel(true) 调用时使用回调或为用户创建 Toast,但我会把这部分留给你。还要确保将此添加到任务的 onPostExecute()

handler.removeCallbacksAndMessages(null);

这将取消处理程序,这样它就不会在成功执行后尝试取消您的任务。

这需要引用您在 onPreExcute() 中调用的处理程序。您可以通过扩展 AsyncTask 并可以维护引用/这些方法调用的 class 来处理。

/**
 * 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();
}