OSDN Git Service

Fix bug in IntentService and Service example code.
authorFlorian Salbrechter <fsalbrechter@google.com>
Mon, 8 Feb 2016 13:36:43 +0000 (13:36 +0000)
committerFlorian Salbrechter <fsalbrechter@google.com>
Tue, 16 Feb 2016 17:37:36 +0000 (17:37 +0000)
Use Thread.sleep instead of Object.wait which simplifies the example.
Also there is a tiny chance, that wait will be called with 0, which
blocks forever.

Change-Id: I4cf90a33089a64bdf802620350f76af08f15f721
(cherry picked from commit 77d8857ed58503669e0659989c02fb7f1ca936b4)

docs/html/guide/components/services.jd

index 8da1694..4053769 100644 (file)
@@ -336,14 +336,11 @@ public class HelloIntentService extends IntentService {
   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() &lt; endTime) {
-          synchronized (this) {
-              try {
-                  wait(endTime - System.currentTimeMillis());
-              } catch (Exception e) {
-              }
-          }
+      try {
+          Thread.sleep(5000);
+      } catch (InterruptedException e) {
+          // Restore interrupt status.
+          Thread.currentThread().interrupt();
       }
   }
 }
@@ -405,14 +402,11 @@ public class HelloService extends Service {
       public void handleMessage(Message msg) {
           // 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() &lt; endTime) {
-              synchronized (this) {
-                  try {
-                      wait(endTime - System.currentTimeMillis());
-                  } catch (Exception e) {
-                  }
-              }
+          try {
+              Thread.sleep(5000);
+          } catch (InterruptedException e) {
+              // Restore interrupt status.
+              Thread.currentThread().interrupt();
           }
           // Stop the service using the startId, so that we don't stop
           // the service in the middle of handling another job