Home | History | Annotate | Download | only in os
      1 /*
      2  * Copyright (C) 2006 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.os;
     18 
     19 import android.app.IAlarmManager;
     20 import android.content.Context;
     21 import android.util.Slog;
     22 
     23 /**
     24  * Core timekeeping facilities.
     25  *
     26  * <p> Three different clocks are available, and they should not be confused:
     27  *
     28  * <ul>
     29  *     <li> <p> {@link System#currentTimeMillis System.currentTimeMillis()}
     30  *     is the standard "wall" clock (time and date) expressing milliseconds
     31  *     since the epoch.  The wall clock can be set by the user or the phone
     32  *     network (see {@link #setCurrentTimeMillis}), so the time may jump
     33  *     backwards or forwards unpredictably.  This clock should only be used
     34  *     when correspondence with real-world dates and times is important, such
     35  *     as in a calendar or alarm clock application.  Interval or elapsed
     36  *     time measurements should use a different clock.  If you are using
     37  *     System.currentTimeMillis(), consider listening to the
     38  *     {@link android.content.Intent#ACTION_TIME_TICK ACTION_TIME_TICK},
     39  *     {@link android.content.Intent#ACTION_TIME_CHANGED ACTION_TIME_CHANGED}
     40  *     and {@link android.content.Intent#ACTION_TIMEZONE_CHANGED
     41  *     ACTION_TIMEZONE_CHANGED} {@link android.content.Intent Intent}
     42  *     broadcasts to find out when the time changes.
     43  *
     44  *     <li> <p> {@link #uptimeMillis} is counted in milliseconds since the
     45  *     system was booted.  This clock stops when the system enters deep
     46  *     sleep (CPU off, display dark, device waiting for external input),
     47  *     but is not affected by clock scaling, idle, or other power saving
     48  *     mechanisms.  This is the basis for most interval timing
     49  *     such as {@link Thread#sleep(long) Thread.sleep(millls)},
     50  *     {@link Object#wait(long) Object.wait(millis)}, and
     51  *     {@link System#nanoTime System.nanoTime()}.  This clock is guaranteed
     52  *     to be monotonic, and is suitable for interval timing when the
     53  *     interval does not span device sleep.  Most methods that accept a
     54  *     timestamp value currently expect the {@link #uptimeMillis} clock.
     55  *
     56  *     <li> <p> {@link #elapsedRealtime} and {@link #elapsedRealtimeNanos}
     57  *     return the time since the system was booted, and include deep sleep.
     58  *     This clock is guaranteed to be monotonic, and continues to tick even
     59  *     when the CPU is in power saving modes, so is the recommend basis
     60  *     for general purpose interval timing.
     61  *
     62  * </ul>
     63  *
     64  * There are several mechanisms for controlling the timing of events:
     65  *
     66  * <ul>
     67  *     <li> <p> Standard functions like {@link Thread#sleep(long)
     68  *     Thread.sleep(millis)} and {@link Object#wait(long) Object.wait(millis)}
     69  *     are always available.  These functions use the {@link #uptimeMillis}
     70  *     clock; if the device enters sleep, the remainder of the time will be
     71  *     postponed until the device wakes up.  These synchronous functions may
     72  *     be interrupted with {@link Thread#interrupt Thread.interrupt()}, and
     73  *     you must handle {@link InterruptedException}.
     74  *
     75  *     <li> <p> {@link #sleep SystemClock.sleep(millis)} is a utility function
     76  *     very similar to {@link Thread#sleep(long) Thread.sleep(millis)}, but it
     77  *     ignores {@link InterruptedException}.  Use this function for delays if
     78  *     you do not use {@link Thread#interrupt Thread.interrupt()}, as it will
     79  *     preserve the interrupted state of the thread.
     80  *
     81  *     <li> <p> The {@link android.os.Handler} class can schedule asynchronous
     82  *     callbacks at an absolute or relative time.  Handler objects also use the
     83  *     {@link #uptimeMillis} clock, and require an {@link android.os.Looper
     84  *     event loop} (normally present in any GUI application).
     85  *
     86  *     <li> <p> The {@link android.app.AlarmManager} can trigger one-time or
     87  *     recurring events which occur even when the device is in deep sleep
     88  *     or your application is not running.  Events may be scheduled with your
     89  *     choice of {@link java.lang.System#currentTimeMillis} (RTC) or
     90  *     {@link #elapsedRealtime} (ELAPSED_REALTIME), and cause an
     91  *     {@link android.content.Intent} broadcast when they occur.
     92  * </ul>
     93  */
     94 public final class SystemClock {
     95     private static final String TAG = "SystemClock";
     96 
     97     /**
     98      * This class is uninstantiable.
     99      */
    100     private SystemClock() {
    101         // This space intentionally left blank.
    102     }
    103 
    104     /**
    105      * Waits a given number of milliseconds (of uptimeMillis) before returning.
    106      * Similar to {@link java.lang.Thread#sleep(long)}, but does not throw
    107      * {@link InterruptedException}; {@link Thread#interrupt()} events are
    108      * deferred until the next interruptible operation.  Does not return until
    109      * at least the specified number of milliseconds has elapsed.
    110      *
    111      * @param ms to sleep before returning, in milliseconds of uptime.
    112      */
    113     public static void sleep(long ms)
    114     {
    115         long start = uptimeMillis();
    116         long duration = ms;
    117         boolean interrupted = false;
    118         do {
    119             try {
    120                 Thread.sleep(duration);
    121             }
    122             catch (InterruptedException e) {
    123                 interrupted = true;
    124             }
    125             duration = start + ms - uptimeMillis();
    126         } while (duration > 0);
    127 
    128         if (interrupted) {
    129             // Important: we don't want to quietly eat an interrupt() event,
    130             // so we make sure to re-interrupt the thread so that the next
    131             // call to Thread.sleep() or Object.wait() will be interrupted.
    132             Thread.currentThread().interrupt();
    133         }
    134     }
    135 
    136     /**
    137      * Sets the current wall time, in milliseconds.  Requires the calling
    138      * process to have appropriate permissions.
    139      *
    140      * @return if the clock was successfully set to the specified time.
    141      */
    142     public static boolean setCurrentTimeMillis(long millis) {
    143         IBinder b = ServiceManager.getService(Context.ALARM_SERVICE);
    144         IAlarmManager mgr = IAlarmManager.Stub.asInterface(b);
    145         if (mgr == null) {
    146             return false;
    147         }
    148 
    149         try {
    150             return mgr.setTime(millis);
    151         } catch (RemoteException e) {
    152             Slog.e(TAG, "Unable to set RTC", e);
    153         } catch (SecurityException e) {
    154             Slog.e(TAG, "Unable to set RTC", e);
    155         }
    156 
    157         return false;
    158     }
    159 
    160     /**
    161      * Returns milliseconds since boot, not counting time spent in deep sleep.
    162      *
    163      * @return milliseconds of non-sleep uptime since boot.
    164      */
    165     native public static long uptimeMillis();
    166 
    167     /**
    168      * Returns milliseconds since boot, including time spent in sleep.
    169      *
    170      * @return elapsed milliseconds since boot.
    171      */
    172     native public static long elapsedRealtime();
    173 
    174     /**
    175      * Returns nanoseconds since boot, including time spent in sleep.
    176      *
    177      * @return elapsed nanoseconds since boot.
    178      */
    179     public static native long elapsedRealtimeNanos();
    180 
    181     /**
    182      * Returns milliseconds running in the current thread.
    183      *
    184      * @return elapsed milliseconds in the thread
    185      */
    186     public static native long currentThreadTimeMillis();
    187 
    188     /**
    189      * Returns microseconds running in the current thread.
    190      *
    191      * @return elapsed microseconds in the thread
    192      *
    193      * @hide
    194      */
    195     public static native long currentThreadTimeMicro();
    196 
    197     /**
    198      * Returns current wall time in  microseconds.
    199      *
    200      * @return elapsed microseconds in wall time
    201      *
    202      * @hide
    203      */
    204     public static native long currentTimeMicro();
    205 }
    206