user3515666
user3515666

Reputation: 25

android.os.NetworkOnMainThreadException, while NOT actually running in MainThread

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

Answers (2)

nKn
nKn

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

Gunaseelan
Gunaseelan

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

Related Questions