user1166635
user1166635

Reputation: 2801

Extending the IntentService class

I have just found following code on official Android site:

  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }

And also I read the following thesis:

So if IntentService uses worker thread and I never have to worry about multi-threading then why I need to use synchronize block in onHandleIntent(...) method? Thank you.

Upvotes: 1

Views: 332

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007286

So if IntentService uses worker thread and I never have to worry about multi-threading then why I need to use synchronize block in onHandleIntent(...) method?

IntentService has a worker thread. onHandleIntent() is called on that thread.

However, lifecycle methods (onCreate(), onStartCommand(), onBind(), onDestroy(), etc.) are called on the main application thread.

If there will be objects you are trying to use from both the worker thread and the main application thread, you will need to synchronize their access by one means or another.

BTW, the code sample you cite is bizarre, and I have no idea why Google is using it. If you need to sleep (unusual in a production app), use SystemClock.sleep().

Upvotes: 1

Related Questions