0

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?

Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
Jehong Ahn
  • 1,872
  • 1
  • 19
  • 25
  • You might consider reading the documentation? `http://developer.android.com/reference/java/lang/Runnable.html` – Simon Mar 22 '14 at 16:37
  • 2
    Off the cuff, it sounds like you should be replacing the sticky service and `Handler` with `AlarmManager` and an `IntentService`, perhaps my `WakefulIntentService`. Don't waste the user's RAM with a service that hangs around just watching the clock tick. As a side benefit, `IntentService`'s `onHandleIntent()` runs on a background thread. – CommonsWare Mar 22 '14 at 16:52

2 Answers2

12

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.

Paul Lammertsma
  • 37,593
  • 16
  • 136
  • 187
4

Runnable just per se is not a Thread. You can use a Runnable to be run inside a Thread, but these are different concepts. You can use an AsyncTask or just define a Thread and use .start() over it.

nKn
  • 13,691
  • 9
  • 45
  • 62