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