0

I have a question about the android main thread within android apps. So when i execute the first block of code i get the error: 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);
    }
}

1 Answers1

0

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. 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.