Reputation: 25
There are many previous questions regarding the android.os.NetworkOnMainThreadException
exception , which is essentially a protective approach by android to prevent us from freezing UI.
Opening a socket from another thread (hence, not the MainThread
) should solve this issue:
Thread t = new Thread (new Runnable() {
@Override
public void run() {
try{
Socket socket = new Socket ( SOME_IP_AS_STRING , SOME_PORT_AS_INT);
// do some IO with socket
}
catch (Exception e) {}
}
});
t.run();
However, this code throws the mentioned exception - android.os.NetworkOnMainThreadException
,
and when debugging (using the Android Studio), it looks like run()
is running under the MainThread
after all, which makes no sense.
where do I got it wrong?
Upvotes: 0
Views: 71
Reputation: 13761
You're calling .run()
which actually will run the Thread
in your main UI
Thread. You need to call .start()
instead to avoid it.
Upvotes: 1
Reputation: 15535
The exception that is thrown when an application attempts to perform a networking operation on its main thread. Try to run your code in AsyncTask
, For more detail refer here
Upvotes: 0