如何在特定时间后杀死异步任务

时间:2014-12-08 13:24:25

标签: android android-asynctask

如何在特定时间后杀死异步任务。

这是我的代码

public class EnterTextAsyc extends AsyncTask<Integer, Integer, Integer> {
    /* displays the progress dialog untill background task is completed */

    @Override
    protected void onPreExecute() {
        progressDialog(context, "Please Wait !!!!!...");
        super.onPreExecute();
    }

    /* Task of EnterTextAsyc performing in the background */
    @SuppressLint("NewApi") @Override
    protected Integer doInBackground(Integer... params) {

        try {
            socket = new Socket(SERVER_IP, SERVERPORT);
            out = new PrintStream(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            out.write(("BE").getBytes());
            ServerData = in.readLine();
            if (ServerData == null || ServerData.equalsIgnoreCase("")) {
                ServerData = "IsNull";
            }

        } catch (NetworkOnMainThreadException e) {
            ServerData = "IsNull";
        } catch (IOException ex) {
            ServerData = "IsNull";
        }

        return null;
    }

如果Server没有响应,如何设置超时消息(ServerData = in.readLine();)。

1 个答案:

答案 0 :(得分:0)

Handler h;
private static final int DELAY=3000; //milis

@Override
protected void onPreExecute() {
    h = new Handler();
    h.postDelayed(new Runnable(){
        public void run() {
            if(h!=null)
                h.removeCallbacksAndMessages(null);
            cancelAfterTimeout(true);
        }
    }, DELAY);
    progressDialog(context, "Please Wait !!!!!...");
    super.onPreExecute();
}

private void cancelAfterTimeout(boolean interrupt){
    //cancel/force interrupt/dissable/remove connection here
    //which you are initializing in doInBackground
    cancel(interrupt);
}

@Override
protected void onPostExecute(Boolean result) {
    if(h!=null)
        h.removeCallbacksAndMessages(null);
}

即使您将mayInterd传递为true,连接仍在执行,您可以创建取消在线连接的新方法,然后super.cancel(true);。更多信息和一些覆盖here - onCanceled()onCanceled(Boolean result)的方法

PS执行时取消Socket连接可能很困难,请关注此here。也许试试HttpClientHTTPConnection