Asynctask 无法显示服务器响应

Asynctask cant display the server response

我在android studio 上创建了一个套接字程序,我想显示服务器的响应。问题是当我使用 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 访问 Activity 级实例变量。这可能并且将会导致内存泄漏。

如果您想要长期 运行 后台任务查看服务 - 然后使用 LocalBroadcastReceiver 将数据传播回您的 Activity / 感兴趣的各方。或者您可以使用像 Otto 或 GreenRobot

这样的事件总线

(可能)出了什么问题

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

您的代码无法正常工作的(可能)原因是因为 AsyncTask 的 doInBackground 方法正在后台线程上 运行 但您正在尝试更新 UI textResponse.setText(serverm) .在 Android 上,对 UI 元素的所有更新都必须在 "main" 或 "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();
}