Android Studio:Thread.sleep()崩溃Void doInBackground()

时间:2018-04-16 00:48:14

标签: android android-studio tcp

基本上如上所述。我有2个AsyncTasks,而Thread.sleep()在一个崩溃,但在我添加它时在另一个工作。

这是在

中工作的任务
public class createConnection extends AsyncTask<Void,Void,Void>{
    @Override
    protected Void doInBackground(Void... params){
        try{
            socket = new Socket(ip, port);
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            InputStream is = socket.getInputStream();
        }
        catch (UnknownHostException e){
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

导致崩溃的任务:

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

    @Override
    protected Void doInBackground(Void... params) {
        out.write(messageToSend);
        out.flush();
        msg.setText("message sent!");

        try{
            Thread.sleep(1000);

            msg.setText("before attempt:");
            byte[] buffer = new byte[4096];
            baos = new ByteArrayOutputStream(4096);

            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1){
                baos.write(buffer, 0, bytesRead);
            }

            String response = baos.toString("UTF-8");
            msg.setText(response);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

我的代码包含一个按钮,用于创建与Python服务器(在Pi上)的TCP连接,以及第二个按钮,用于在两者之间发送和接收文本。在msg文本框中,应用程序显示&#34;已发送消息!&#34;在它崩溃之前,但在尝试之前没有到达#34;这导致我认为它是Thread.sleep()崩溃了应用程序。有没有人知道为什么它崩溃或为什么它在一个功能而不是另一个功能?

1 个答案:

答案 0 :(得分:1)

您无法从msg.setText(...)内拨打doInBackground()。这肯定会导致异常。您可以使用AsyncTask的进度机制发布进度更新:

public class SR extends AsyncTask<Void,String,Void> { // <- NOTE TYPE CHANGE

    @Override
    protected Void doInBackground(Void... params) {
        out.write(messageToSend);
        out.flush();
        publishProgress("message sent!");

        try{
            Thread.sleep(1000);

            publishProgress("before attempt:");
            byte[] buffer = new byte[4096];
            baos = new ByteArrayOutputStream(4096);

            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1){
                baos.write(buffer, 0, bytesRead);
            }

            String response = baos.toString("UTF-8");
            publishProgress(response);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void onProgressUpdate(String... progress) {
        msg.setText(progress[0]);
    }
}