我在一个应用程序上工作,该应用程序有两个活动。 MainActivity必须使用editext才能将IP地址和带有Intent的端口发送到第二个Activity2。
我遇到的问题是当我使用Handler.post()
来更新UI线程中的TextView时,应用程序崩溃了。没有处理程序线程app正确运行。我认为我的代码是正确的,但我无法理解这个问题的原因。
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();
答案 0 :(得分:3)
问题是您在创建活动对象后创建了处理程序对象。
准备好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();