I'm using the following code in my onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(9002);
Socket s = serverSocket.accept();
DataOutputStream outputStream = new DataOutputStream(
s.getOutputStream());
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(s.getInputStream()));
outputStream.write("Howdy! newbie".getBytes());
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.run();
}
});
}
It gives me a NetworkOnMainThreadException!
It does work when I use the following lines to remove the restriction:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But why should I use it?
I used thread, why isn't it running on the separated thread and runs on the UI thread?!
Change
thread.run();
to
thread.start();
Difference:
Thread.run() does not spawn a new thread whereas Thread.start() does, i.e
Thread.runactually runs on the same thread as that of the caller whereasThread.start()creates a new thread on which the task is run.
For more info see Difference between running and starting a thread
Because you are not asking the thread to start.
Replace:
thread.run();
With
thread.start();
Calling run() will simply execute the provided Runnable on the current thread. However, start() will spawn the execution onto a new thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With