原代碼如下,如果我不用BUTTON去觸發的話是可以建立SOCKET的,但是用上BUTTON,把建立SOCKET的方法放到子線程中,仍然exception會顯示不能再主線程中使用網絡操作,真心求解為什麼,看了2天了,剛學JAVA,不太理解。
package com.example.xlguang.wifi;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends ActionBarActivity {
private EditText editText;
private Button button;
private TextView MTextview;
Handler handler=new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText1);
button = (Button)findViewById(R.id.button1);
final RunnableThread runnable = new RunnableThread();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handler.post(runnable);
}
});
}
public class RunnableThread implements Runnable
{
public void run() {
Socket socket = null;
String message = editText.getText().toString()+ "\r\n" ;
try {
//創建客戶端socket,注意:不能用localhost或127.0.0.1,Android模擬器把自己作為localhost
socket = new Socket("172.16.5.30",8000);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter
(socket.getOutputStream())),true);
//發送數據
out.println(message);
//接收數據
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = in.readLine();
if (null != msg){
editText.setText(msg);
System.out.println(msg);
}
else{
editText.setText("data error");
}
out.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if (null != socket){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
handler.post(runnable); //這是運行在UI線程中的,android會把runnable放到UI線程的消息循環中進行分支處理
所以改成
new Thread(runnable).start();