1

当我尝试连接到 wifi 路由时,这是我的代码,但我显示错误

Button.OnClickListener buttonConnectOnClickListener = new Button.OnClickListener(){
    @Override
    public void onClick(View arg0) {

        connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        wifiInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (wifiInfo.isConnected()) {

        if(!connected){

             try {
                // socket = new Socket("192.168.1.1", 2001);
            // Log.v("test4","test4");
             /*Toast msg = Toast.makeText(Main.this,
             "Connected Successfully", Toast.LENGTH_LONG);
             msg.show();*/
             //Log.v("test5","test5");
             socket = new Socket("192.168.1.1",2001);
                  dataOutputStream = new DataOutputStream(socket.getOutputStream());
                  changeConnectionStatus(true);} 
             catch (UnknownHostException e) {changeConnectionStatus(false);} 
             catch (IOException e) {changeConnectionStatus(false);}}
        else{
            try {socket.close();
            Toast msg = Toast.makeText(Main.this,
            "Disconnected Successfully", Toast.LENGTH_LONG);
            msg.show();
                  changeConnectionStatus(false);} 
            catch (UnknownHostException e) {changeConnectionStatus(false);}
            catch (IOException e) {changeConnectionStatus(false);}}}
        else {Toast msg = Toast.makeText(Main.this,
                "Wifi is not connected !", Toast.LENGTH_LONG);
                msg.show();}
}};

logcat 中的错误是

06-26 18:37:48.190: W/dalvikvm(11911): threadid=1: 线程退出未捕获异常 (group=0x40a571f8) 06-26 18:37:48.205: E/AndroidRuntime(11911): 致命异常: main 06-26 18:37:48.205: E/AndroidRuntime(11911): android.os.NetworkOnMainThreadException 06-26 18:37:48.205: E/AndroidRuntime(11911): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode. java:1099) 06-26 18:37:48.205: E/AndroidRuntime(11911): 在 libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)

4

3 回答 3

2

您正试图在主应用程序线程上打开一个套接字。网络 I/O 需要在后台线程上进行,因此不会占用用户界面。

于 2013-06-26T10:54:48.000 回答
1

正如许多人所提到的,AsyncTask 是最简单的启动方式。您可以在此处找到快速教程:AsyncTask

于 2013-06-26T10:59:21.443 回答
0

您正在尝试在 main 上使用互联网,Thread这是不可能的,因此对于这个问题,请将您的try-catch代码放入AsyncTask.

编辑:

带有线程、处理程序和的 Android 后台处理 - Vogella可能会对您有所帮助。

于 2013-06-26T10:55:09.097 回答