SystemClock.java revision 54b6cfa9a9e5b861a9930af873580d6dc20f773c
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
17package android.os;
18
19
20/**
21 * Core timekeeping facilities.
22 *
23 * <p> Three different clocks are available, and they should not be confused:
24 *
25 * <ul>
26 *     <li> <p> {@link System#currentTimeMillis System.currentTimeMillis()}
27 *     is the standard "wall" clock (time and date) expressing milliseconds
28 *     since the epoch.  The wall clock can be set by the user or the phone
29 *     network (see {@link #setCurrentTimeMillis}), so the time may jump
30 *     backwards or forwards unpredictably.  This clock should only be used
31 *     when correspondence with real-world dates and times is important, such
32 *     as in a calendar or alarm clock application.  Interval or elapsed
33 *     time measurements should use a different clock.
34 *
35 *     <li> <p> {@link #uptimeMillis} is counted in milliseconds since the
36 *     system was booted.  This clock stops when the system enters deep
37 *     sleep (CPU off, display dark, device waiting for external input),
38 *     but is not affected by clock scaling, idle, or other power saving
39 *     mechanisms.  This is the basis for most interval timing
40 *     such as {@link Thread#sleep(long) Thread.sleep(millls)},
41 *     {@link Object#wait(long) Object.wait(millis)}, and
42 *     {@link System#nanoTime System.nanoTime()}.  This clock is guaranteed
43 *     to be monotonic, and is the recommended basis for the general purpose
44 *     interval timing of user interface events, performance measurements,
45 *     and anything else that does not need to measure elapsed time during
46 *     device sleep.  Most methods that accept a timestamp value expect the
47 *     {@link #uptimeMillis} clock.
48 *
49 *     <li> <p> {@link #elapsedRealtime} is counted in milliseconds since the
50 *     system was booted, including deep sleep.  This clock should be used
51 *     when measuring time intervals that may span periods of system sleep.
52 * </ul>
53 *
54 * There are several mechanisms for controlling the timing of events:
55 *
56 * <ul>
57 *     <li> <p> Standard functions like {@link Thread#sleep(long)
58 *     Thread.sleep(millis)} and {@link Object#wait(long) Object.wait(millis)}
59 *     are always available.  These functions use the {@link #uptimeMillis}
60 *     clock; if the device enters sleep, the remainder of the time will be
61 *     postponed until the device wakes up.  These synchronous functions may
62 *     be interrupted with {@link Thread#interrupt Thread.interrupt()}, and
63 *     you must handle {@link InterruptedException}.
64 *
65 *     <li> <p> {@link #sleep SystemClock.sleep(millis)} is a utility function
66 *     very similar to {@link Thread#sleep(long) Thread.sleep(millis)}, but it
67 *     ignores {@link InterruptedException}.  Use this function for delays if
68 *     you do not use {@link Thread#interrupt Thread.interrupt()}, as it will
69 *     preserve the interrupted state of the thread.
70 *
71 *     <li> <p> The {@link android.os.Handler} class can schedule asynchronous
72 *     callbacks at an absolute or relative time.  Handler objects also use the
73 *     {@link #uptimeMillis} clock, and require an {@link android.os.Looper
74 *     event loop} (normally present in any GUI application).
75 *
76 *     <li> <p> The {@link android.app.AlarmManager} can trigger one-time or
77 *     recurring events which occur even when the device is in deep sleep
78 *     or your application is not running.  Events may be scheduled with your
79 *     choice of {@link java.lang.System#currentTimeMillis} (RTC) or
80 *     {@link #elapsedRealtime} (ELAPSED_REALTIME), and cause an
81 *     {@link android.content.Intent} broadcast when they occur.
82 * </ul>
83 */
84public final class SystemClock {
85    /**
86     * This class is uninstantiable.
87     */
88    private SystemClock() {
89        // This space intentionally left blank.
90    }
91
92    /**
93     * Waits a given number of milliseconds (of uptimeMillis) before returning.
94     * Similar to {@link java.lang.Thread#sleep(long)}, but does not throw
95     * {@link InterruptedException}; {@link Thread#interrupt()} events are
96     * deferred until the next interruptible operation.  Does not return until
97     * at least the specified number of milliseconds has elapsed.
98     *
99     * @param ms to sleep before returning, in milliseconds of uptime.
100     */
101    public static void sleep(long ms)
102    {
103        long start = uptimeMillis();
104        long duration = ms;
105        boolean interrupted = false;
106        do {
107            try {
108                Thread.sleep(duration);
109            }
110            catch (InterruptedException e) {
111                interrupted = true;
112            }
113            duration = start + ms - uptimeMillis();
114        } while (duration > 0);
115
116        if (interrupted) {
117            // Important: we don't want to quietly eat an interrupt() event,
118            // so we make sure to re-interrupt the thread so that the next
119            // call to Thread.sleep() or Object.wait() will be interrupted.
120            Thread.currentThread().interrupt();
121        }
122    }
123
124    /**
125     * Sets the current wall time, in milliseconds.  Requires the calling
126     * process to have appropriate permissions.
127     *
128     * @return if the clock was successfully set to the specified time.
129     */
130    native public static boolean setCurrentTimeMillis(long millis);
131
132    /**
133     * Returns milliseconds since boot, not counting time spent in deep sleep.
134     * <b>Note:</b> This value may get reset occasionally (before it would
135     * otherwise wrap around).
136     *
137     * @return milliseconds of non-sleep uptime since boot.
138     */
139    native public static long uptimeMillis();
140
141    /**
142     * Returns milliseconds since boot, including time spent in sleep.
143     *
144     * @return elapsed milliseconds since boot.
145     */
146    native public static long elapsedRealtime();
147
148    /**
149     * Returns milliseconds running in the current thread.
150     *
151     * @return elapsed milliseconds in the thread
152     */
153    public static native long currentThreadTimeMillis();
154}
155