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);
}
}