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?
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?
Runnable
just per se is not aThread
. You can use aRunnable
to be run inside aThread
, but these are different concepts. You can use anAsyncTask
or just define aThread
and use.start()
over it.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:
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):
The primary difference here is that Thread's
start()
method takes care of the logic for spawning a new thread and executing the Runnable'srun()
inside it.Android's AsyncTask further facilitates thread execution and callbacks onto the main thread, but the concept is the same.