Asynctask无法显示服务器响应

时间:2015-05-20 02:42:54

标签: 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;
    }

}                 

2 个答案:

答案 0 :(得分:1)

什么(可能)错了

看起来您正在尝试不断轮询服务器并更新文本字段。 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();
}

答案 1 :(得分:0)

您不应该从AsyncTask访问活动级实例变量。这会导致内存泄漏。

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

这样的事件总线