我正在开发一个应用程序,该应用程序有两个 Activity 。 MainActivity 必须编辑文本才能将 IP 地址和端口以及 Intent 发送到第二个 Activity2。
我遇到的问题是,当我使用 Handler.post() 来更新 UI 线程中的 TextView 时,应用程序崩溃。没有处理程序线程应用程序正确运行。我认为我的代码是正确的,但我无法理解这个问题的原因。
public class Activity2 extends Activity {
private Socket s;
private OutputStream out = null;
private PrintWriter w = null;
private Handler handler = new Handler();
private TextView textView1;
private String tag = "ALEX";
private static String IP;
private static int port;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
IP = extras.getString("IP");
String port2 = extras.getString("PORT");
port = Integer.parseInt(port2);
// Log.v("ip",ip);
// Log.v("port",port);
}
Runnable runnable = new Runnable() {
public void run() {
synchronized (this) {
try {
s = new Socket(IP, port);
out = s.getOutputStream();
w = new PrintWriter(out);
} catch (Exception e) {
Log.v("error socket", "Alex soc");
e.printStackTrace();
}
}
**handler.post(new Runnable() {
@Override
public void run() {
synchronized (this) {
try {
Thread.sleep(1000);
if (s.isConnected)
textView1.setText("connected...");
// textView1.setText("not connected...");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.v("error handler", "handler Alex");
e.printStackTrace();
}
}
}
});**
}
};
Thread mythread = new Thread(runnable);
mythread.start();
最佳答案
问题是,一旦创建了 Activity 对象,您就正在创建处理程序对象。
处理程序应在 Looper 之后创建已经准备好了。
所以你的代码应该是这样的:
private Handler handler;
private TextView textView1;
private String tag = "ALEX";
private static String IP;
private static int port;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
handler = new Handler();
关于android - Handler.post() 线程正在使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20442589/