【问题标题】:how to kill Async task after a specific time如何在特定时间后终止异步任务
【发布时间】:2014-12-08 22:11:03
【问题描述】:

如何在特定时间后终止异步任务。

这是我的代码

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

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

【问题讨论】:

  • 你可以使用定时器或线程,可以运行来倒计时你想要的时间,x毫秒后你可以杀死异步任务
  • 这里对超时的处理应该直接在socket中设置。

标签: android android-asynctask


【解决方案1】:
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);
}

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

PS 在执行时取消Socket 连接可能很困难,请讨论这个here。也许试试HttpClientHTTPConnection

【讨论】:

  • 这个解决方案解决了我的问题,但我无法取消 Socket 连接,它的运行背景。请帮帮我?
  • 就像我在上一段中建议的那样:使用 HttpClient 或 HttpConnecion 或其他“可取消”方法。此处为简单的 httpClient 和 GET 方法的示例:stackoverflow.com/questions/5400258/…
  • 我不想使用另一个连接,没有办法取消套接字连接??。我正在使用 socket.close();但此代码不适用于 mi。
  • Socket 连接只能由服务器端取消,据我所知......有Socket.close(); 方法,但仅标记isClosed() 的连接。检查thisthis 线程,也许它可以帮助你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2015-12-18
  • 1970-01-01
相关资源
最近更新 更多