Search code examples
androidrunnablenetworkonmainthread

NetworkOnMainThreadException on Runnable


I am making Android 4.4 project. I've got NetworkOnMainThreadException. Below is my process.

Service(sticky) -> Handler(per 5 minutes) -> Runnable -> HttpPost

Isn't Runnable a separate thread? Shoud I use AsyncTask in Runnable?


Solution

  • Runnable is a simple interface, that, as per the Java documentation, "should be implemented by any class whose instances are intended to be executed by a thread." (Emphasis mine.)

    For instance, defining a Runnable as follows will simply execute it in the same thread as it's created:

    new Runnable() {
        @Override
        public void run() {
            Log.d("Runnable", "Hello, world!");
        }
    }.run();
    

    Observe that all you're actually doing here is creating a class and executing its public method run(). There's no magic here that makes it run in a separate thread. Of course there isn't; Runnable is just an interface of three lines of code!

    Compare this to implementing a Thread (which implements Runnable):

    new Thread() {
        @Override
        public void run() {
            Log.d("Runnable", "Hello, world!");
        }
    }.start();
    

    The primary difference here is that Thread's start() method takes care of the logic for spawning a new thread and executing the Runnable's run() inside it.

    Android's AsyncTask further facilitates thread execution and callbacks onto the main thread, but the concept is the same.