我的应用程序卡住了,如何在其中实现线程?

4

您能帮我想办法如何实现线程,以便在等待服务器的答复时不会冻结吗?我已经尝试了五个小时左右,但是我无法找到使用线程的方法,然后将其返回以使用tv.setText()设置文本。

package zee.rhs.dk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidClientActivity extends Activity {

private String ip = "90.184.254.246";
private int port = 8081;
private String line;
private TextView tv;
private Button btn;
private Socket socket;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv = (TextView) findViewById(R.id.tv);
    btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                socket = new Socket(ip, port);
                out = new PrintWriter(socket.getOutputStream(), true);
                out.println("update");

                in = new BufferedReader(new InputStreamReader(socket
                        .getInputStream()));

                while ((line = in.readLine()) == null) {
                }
                tv.setText(line);

            } catch (UnknownHostException e) {
                Toast.makeText(AndroidClientActivity.this,
                        "Can't reach ip: " + ip, Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } catch (IOException e) {
                Toast.makeText(AndroidClientActivity.this,
                        "Accept failed at port: " + port, Toast.LENGTH_LONG)
                        .show();
                e.printStackTrace();
            } finally {
                out.close();
            }
        }
    });
}
}

out.println("update");之后尝试过使用out.flush();吗? - srkavin
http://developer.android.com/resources/articles/painless-threading.html - kmb64
2个回答

4

AsyncTask 是您需要的内容。以下是帮助页面上的说明:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

请记住: doInBackground 在单独的线程中运行,onPostExecutedoInBackground 完成后在 UI 线程中运行。


1
将负责向服务器发送请求的代码放入单独的线程中:
Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            // put your socket operations here   
        } catch (InterruptedException e) {
           // handle exception if you need
        }
    }
};

thread.start();

问题在于,您不允许从UI线程以外的另一个线程更改UI。您需要使用Handler或其他方法来通知UI线程进行视图更新。 - Simon Forsberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接