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

标签 java android multithreading freeze

你能帮我弄清楚如何为此实现线程,这样它就不会在等待服务器响应时卡住吗? 我已经尝试了 5 个小时左右,我只是找不到在线程中使用它的方法,然后返回它以使用 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();
            }
        }
    });
}
}

最佳答案

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 线程中运行。

关于java - 我的应用程序卡住,如何在其中实现线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10507171/

相关文章:

java - 尝试从 Spring 中的 WEB-INF 目录读取属性文件时出错

java.lang.OutOfMemoryError : unable to create new native thread ..在Windows中重新创建

java - 服务器和线程模型

python - Python 线程中进行多个 stdout w/flush

java - capturePicture() 将结果位图放入内存不足

java - 返回函数和存储变量有什么区别?

java - RESTFul Web 服务 POST 示例

java - 为什么 void method1(T obj) 不允许泛型?

android - 如何在 Android 的 WebView 中读取 Blob 中的数据?

android - 将Gradle从2.14升级到4.6