2012-03-08 29 views
0

运行我在这使得程序下面的代码的插座,当我在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(); 
      } 
     } 
     }); 
    } 
} 

回答

2

您好,我有同样的问题(Windows 7中,Android的4.03)。我已经解决了采用了android 2.33(API等级10)和仿真器与Android 2.33内核的问题。

1

您是否在AndroidManifest.xml中设置了Internet权限?

您需要这条线:

<uses-permission android:name="android.permission.INTERNET" /> 
+1

是的,我添加此权限在AndroidManifest.xml 但单击按钮时错误还是发生了.. – 2012-03-08 07:28:45

+1

然后,我建议你使用的logcat工具在Eclipse中看到发生了什么。通常你会得到一个错误信息有一个堆栈跟踪在那里你能看到事情会出错一起。 – Petter 2012-03-08 07:33:07

+1

使用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

1

你应该通过这个命令在adb转发从PC到AVD端口:

adb forward tcp:YOUR_PORT_NUM tcp:YOUR_PORT_NUM