運行我在這使得程序下面的代碼的插座,當我在AVD運行它停止工作(很遺憾,您-app-已停止),我使用Android 4.0平臺上的一個問題Windows 7的.. 我試圖移動插座部分,按一下按鈕,所以當我點擊按鈕,程序停止在插座定義的工作,所以在這裏做了錯誤。 (Socket socket;)Android的套接字錯誤當AVD
public class ServerClient extends Activity {
// declaration of button, textView
private Button bt;
private TextView tv;
//port number
private static final int REDIRECTED_SERVERPORT = 5000;
//ip address
private String serverIpAddress = "10.0.2.2";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
// on click on the button the socket will be created
bt.setOnClickListener(new OnClickListener() {
Socket socket; //this line cause the app to stop working
public void onClick(View v) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
是的,我添加此權限在AndroidManifest.xml 但單擊按鈕時錯誤還是發生了.. – 2012-03-08 07:28:45
然後,我建議你使用的logcat工具在Eclipse中看到發生了什麼。通常你會得到一個錯誤信息有一個堆棧跟蹤在那裏你能看到事情會出錯一起。 – Petter 2012-03-08 07:33:07
使用LogCat時發生以下錯誤... 03-07 20:52:00.056:E/AndroidRuntime(571):java.lang.RuntimeException:無法啓動活動ComponentInfo {com.app.ServerClient/com.app.ServerClient.ServerClient}:android.os.NetworkOnMainThreadException – 2012-03-08 07:44:47