多个按钮按下AsyncTasks冻结UI

时间:2018-02-05 22:51:44

标签: java android

我有一个执行AsyncTask HTTP Get请求的按钮。但是,多次快速按下此按钮通常会冻结处于按下状态的按钮UI(它使用XML selector)并且我不确定原因。我认为AsyncTasks并没有影响用户界面。有人可以提供有关为什么按钮有时会冻结的见解吗?

我已经尝试executeexecuteOnExecutor没有区别。

onClickListener

iv.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        if (buttonEvent > 0) {
            String url = "bogusurl" + buttonEvent.toString();
            System.out.println(url);
            try {
                HTTPRequest request = new HTTPRequest();
                //request.execute(url).get();
                request.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url).get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (jumpPage > 0) {
            loadPage(jumpPage);
        }
    }
});

AsyncTask类本身:

public class HTTPRequest extends AsyncTask<String, Void, Void> {
    private static final int CONNECTION_TIMEOUT = 3000;

    @Override
    protected Void doInBackground(String... params) {
        String stringUrl = params[0];
        URL myUrl;
        HttpURLConnection connection = null;

        try {
            myUrl = new URL(stringUrl);

            connection = (HttpURLConnection) myUrl.openConnection();

            connection.setRequestMethod("GET");
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            Log.d("Request", "Sending command");
            connection.connect();
            InputStream in = connection.getInputStream();
            in.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

AsyncTask documentation中所述,

  

get()方法将等待计算完成所需,然后检索其结果。

删除get()方法。因此,您的主线程正在等待后台任务的响应。

如果要处理AsyncTask类的结果,则最好覆盖onPostExecute(Result result)。它在doInBackground(Params... params)之后运行,结果为。