android - Asynctask 无法显示服务器响应

标签 android sockets android-studio android-asynctask tcpclient

我在android studio上创建了一个socket程序,我想显示服务器的响应。问题是当我使用 textResponse.setText(serverm);它没有用。这是我在 asynctask 上的代码

private class Connect extends AsyncTask<Void, Void, Void> {

    final String address = editTextAddress.getText().toString();


    String textResponse = null;
    String serverm = null;
    @Override
    protected Void doInBackground(Void... params) {
        mRun = true;

            try {
                client = new Socket(address, 3818);
                mBufferIn = new BufferedReader(new InputStreamReader(client.getInputStream()));


                while (mRun) {
                    serverm = mBufferIn.readLine();

                    if (serverm != null) {
                        System.out.println(serverm);
                        textResponse.setText(serverm);


                    }
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return null;
    }

}                 

最佳答案

(可能)出了什么问题

看起来您正在尝试连续轮询服务器并更新文本字段。 AsyncTask 可能不是实现此目的的最佳工具选择。 AsyncTasks 的典型用例是您有一项需要很长时间的工作,并且您希望在完成后更新 UI。

您的代码无法正常工作的(可能)原因是 AsyncTask 的 doInBackground 方法正在后台线程上运行,但您正在尝试更新 UI textResponse.setText(serverm)。在 Android 上,对 UI 元素的所有更新都必须在“主”或“UI”线程上发生。您的代码可能会在此行抛出异常并终止 AsyncTask。

建议

我认为一个简单的后台线程以及在您有更新时发布到 UI 线程会更自然。使用此方案,您将拥有一个长期存在的线程,您可以在该线程上执行网络,当 UI 需要更新时,它将安排在 UI 线程上完成的工作。

// Create an android.os.Handler that you can use to post Runnables 
// to the UI thread.
private static final Handler UI_HANDLER = new Handler(Looper.getMainLooper());

// Create a Runnable that will poll a server and send updates to the
// UI thread.
private final Thread mConnectAndPoll = new Thread(new Runnable() {

    @Override
    public void run() {
        mRun = true;
        try {
            String address = editTextAddress.getText().toString();
            client = new Socket(address, 3818);
            mBufferIn = new BufferedReader(
                    new InputStreamReader(client.getInputStream()));

            while (mRun) {
                serverm = mBufferIn.readLine();

                if (serverm != null) {
                    System.out.println(serverm);
                    // Create a Runnable that will update the 
                    // textResponse TextView with the response from
                    // the server, and schedule it to run on the UI 
                    // thread.
                    UI_HANDLER.post(new UpdateResponseRunnable(serverm));
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

// Create a subclass of Runnable that will update textResponse.
private class UpdateResponseRunnable implements Runnable {
    private final String mValue;

    public UpdateResponseRunnable(String value) {
        mValue = value;
    }

    @Override
    public void run() {
        textResponse.setText(mValue);
    }
};

// Start the background thread in onCreate or wherever you are
// currently starting your AsyncTask.
@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    mConnectAndPoll.start();
}

关于android - Asynctask 无法显示服务器响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339417/

相关文章:

android - Android : Pointing out the correct image in texture coordinate buffers 上的 VBO

Android避免缓存

java - 如何更改 MPAndroidChart PieChart 中的百分比文本颜色?

c# - 连接的TCP套接字如何同时发送/接收多个文件?

java - 方法调用可能会产生 java.lang.nullpointerException

java - 多次调用 Button 的 OnClickListener

java - 使用 Java 连接到缓存 (InterSystems) 数据库

java - 如何使用套接字 channel 读写数据和接受连接

java - 无法从简单的 Java 代理服务器查看数据

android - MacOS android studio NDK 通过使用 ndk.dir 属性进行定位。该方法已被弃用