简体   繁体   English

为什么我的线程没有像我认为的那样做?(Android internet over main thread问题)

[英]Why does my thread not do what i think it does?(Android internet over main thread issue)

I have a question about the android main thread within android apps.我对 android 应用程序中的 android 主线程有疑问。 So when i execute the first block of code i get the error: android.os.NetworkOnMainThreadException .所以当我执行第一块代码时,我得到了错误: android.os.NetworkOnMainThreadException And i do not understand why, i am starting the thread as well as performing tasks when the thread is started.而且我不明白为什么,我正在启动线程以及在线程启动时执行任务。 WHY does the application still get run on the main thread?为什么应用程序仍然在主线程上运行? And why does the code beneath the first block do the trick?为什么第一个块下面的代码会起作用?

public class MainActivity extends AppCompatActivity {
    ClientSocket clientSocket = new ClientSocket();

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        clientSocket.start();
        try {
            clientSocket.startConnection("192.168.2.5", 45032);
            clientSocket.sendMessage("test");
        } catch (IOException e) {
            e.printStackTrace();
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
} 

What does end up working:什么最终起作用:

public class MainActivity extends AppCompatActivity {
    ClientSocket clientSocket = new ClientSocket();

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        new Thread(() -> {
            try {
                clientSocket.startConnection("192.168.2.5", 45032);
                clientSocket.sendMessage("test");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

As you already pointed out yourself, opening the socket connection in a separate thread solves the problem!正如您已经指出的那样,在单独的线程中打开套接字连接可以解决问题!

Everything you directly execute in the onCreate() method will be run on the main thread.您在onCreate()方法中直接执行的所有内容都将在主线程上运行。 In general you shouldn't perform network tasks on the main-thread, as this could have a significant impact on the responsiveness of your app, especially in areas with a bad internet connection.一般来说,您不应该在主线程上执行网络任务,因为这可能会对您的应用程序的响应能力产生重大影响,尤其是在互联网连接不良的地区。

So, establishing the connection in a separate thread is the right thing to do!因此,在单独的线程中建立连接是正确的做法!

More on this particular error. 有关此特定错误的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM