Android如何等待AsyncTask完成

时间:2016-02-20 19:56:17

标签: android android-asynctask

我有一个AsyncTask作为客户端,从服务器获取一个字符串并将其放在String中。在任务之后,我使用来自服务器的响应,但数据尚未更改 - 它为空。

connectBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ...
        Client myClient = new Client(responseTV);
        myClient.execute();

        if (responseStr.charAt(0) == '1') {   <----- responseStr is null
            changeBrightness(Integer.parseInt(responseStr.substring(1)));
        }
    }
});

我认为代码在.execute()之后继续进行,这在我的情况下并不是很好。

更新:为客户端类添加了代码。

public class Client extends AsyncTask<Void, Void, Void> {

    String response = "";
    TextView responseTV;

    public Client(TextView responseTV) {
        this.responseTV = responseTV;
    }

    @Override
    protected Void doInBackground(Void... params) {
        Socket socket = null;

        try {
            socket = new Socket(IP, PORT);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];

            int bytesRead;
            InputStream inputStream = socket.getInputStream();

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            e.printStackTrace();
            response = "IOException: " + e.toString();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        //Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
        responseTV.setText(response);
        responseStr = response;
        super.onPostExecute(aVoid);
    }
}

1 个答案:

答案 0 :(得分:3)

if (responseStr.charAt(0) == '1') {   <----- responseStr is null
            changeBrightness(Integer.parseInt(responseStr.substring(1)));
        }

onPostExecute()的{​​{1}}方法中使用此代码。它在AsyncTask上运行,正是您在UI thread完成工作后所需的方法。