【问题标题】:Java code wont work in android studio. Port communication [duplicate]Java 代码无法在 android studio 中运行。端口通信 [重复]
【发布时间】:2019-02-09 17:46:18
【问题描述】:

此代码在 Eclipse 中运行良好,但是当我尝试在 android studio 中运行它时出现错误。我是学习java的新手,不知道如何调试它。 创建新套接字时会发生错误,但在eclipse中可以正常工作。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Host IP.
    String hostName = "192.168.0.3";
    //Port Number.
    int portNumber = 6666;
    try (
        //Create a connection with IP on selected port.
        Socket echoSocket = new Socket(hostName, portNumber);
        //Create an outputStream with the connection.
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
    ) {
        //Send data out the outputStream to server.
        out.println("Hello");
        //Exit so server knows to wait for the next connection.
        System.exit(1);
        //Catch Exceptions
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host " + hostName);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to " +
        hostName);
        System.exit(1);
    }
}

02-09 17:48:09.920 13635-13635/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-09 17:48:09.970 13635-13635/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.geodesick.testapp, PID: 13635
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.geodesick.testapp/com.geodesick.testapp.MainActivity}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
        at android.app.ActivityThread.access$900(ActivityThread.java:175)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5603)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
        at java.net.InetAddress.getAllByName(InetAddress.java:214)
        at java.net.Socket.tryAllAddresses(Socket.java:109)
        at java.net.Socket.<init>(Socket.java:178)
        at java.net.Socket.<init>(Socket.java:150)
        at com.geodesick.testapp.MainActivity.onCreate(MainActivity.java:28)
        at android.app.Activity.performCreate(Activity.java:5458)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471) 
        at android.app.ActivityThread.access$900(ActivityThread.java:175) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:146) 
        at android.app.ActivityThread.main(ActivityThread.java:5603) 
        at java.lang.reflect.Method.invokeNative(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:515) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
        at dalvik.system.NativeStart.main(Native Method) 

【问题讨论】:

标签: java android sockets networkonmainthread


【解决方案1】:

您不能在 Android UI 主线程上运行网络操作。

这是一个在其自己的线程上运行 Asynctask 的解决方案:

class DoSocketOperation extends AsyncTask<String, Void, YourResult result> {
    protected YourResult doInBackground(String... urls) {
        // custom class to transport network result(you create it)
        YourResult result = nesw YourResult();
        //Host IP.
        String hostName = "192.168.0.3";
        //Port Number.
        int portNumber = 6666;
        try {
                //Create a connection with IP on selected port.
                Socket echoSocket = new Socket(hostName, portNumber);
                //Create an outputStream with the connection.
                PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);

                //Send data out the outputStream to server.
                out.println("Hello");
                result.setSucessOrSometing(true); (you create this)
                //Catch Exceptions
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                    hostName);
            System.exit(1);
        }
        return YourResult;
    }

    protected void onPostExecute(YourResult result) {

        if(result != null){
            // Now your on the main ui thread again, do something on the main ui thread with the result
        }
    }
}

【讨论】:

  • 天哪!我想我应该刚刚在 android 中启动它!我已经跳过循环好几天了。 java很难!
  • @erik:如果通过简单地发布指向另一个重复问题的链接来回答问题,那么不要回答它,而是投票关闭作为重复问题。跨度>
  • 感谢 Erik 。“您不能在 Android UI 主线程上运行网络操作”
  • 抄袭重复问题的答案中的代码并不能真正帮助改变这个答案的状态。请考虑删除
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 2020-02-26
相关资源
最近更新 更多