Ringer.java revision a639e43e02e2b395285ccacabdb9c57943b486a1
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 com.android.phone;
18
19import android.content.Context;
20import android.media.AudioManager;
21import android.media.Ringtone;
22import android.media.RingtoneManager;
23import android.net.Uri;
24import android.os.Handler;
25import android.os.IPowerManager;
26import android.os.Looper;
27import android.os.Message;
28import android.os.RemoteException;
29import android.os.ServiceManager;
30import android.os.SystemClock;
31import android.os.SystemProperties;
32import android.os.Vibrator;
33import android.provider.Settings;
34import android.util.Log;
35
36import com.android.internal.telephony.Phone;
37/**
38 * Ringer manager for the Phone app.
39 */
40public class Ringer {
41    private static final String LOG_TAG = "Ringer";
42    private static final boolean DBG =
43            (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
44
45    private static final int PLAY_RING_ONCE = 1;
46    private static final int STOP_RING = 3;
47
48    private static final int VIBRATE_LENGTH = 1000; // ms
49    private static final int PAUSE_LENGTH = 1000; // ms
50
51    /** The singleton instance. */
52    private static Ringer sInstance;
53
54    // Uri for the ringtone.
55    Uri mCustomRingtoneUri = Settings.System.DEFAULT_RINGTONE_URI;
56
57    Ringtone mRingtone;
58    Vibrator mVibrator;
59    IPowerManager mPowerManager;
60    volatile boolean mContinueVibrating;
61    VibratorThread mVibratorThread;
62    Context mContext;
63    private Worker mRingThread;
64    private Handler mRingHandler;
65    private long mFirstRingEventTime = -1;
66    private long mFirstRingStartTime = -1;
67
68    /**
69     * Initialize the singleton Ringer instance.
70     * This is only done once, at startup, from PhoneApp.onCreate().
71     */
72    /* package */ static Ringer init(Context context) {
73        synchronized (Ringer.class) {
74            if (sInstance == null) {
75                sInstance = new Ringer(context);
76            } else {
77                Log.wtf(LOG_TAG, "init() called multiple times!  sInstance = " + sInstance);
78            }
79            return sInstance;
80        }
81    }
82
83    /** Private constructor; @see init() */
84    private Ringer(Context context) {
85        mContext = context;
86        mPowerManager = IPowerManager.Stub.asInterface(ServiceManager.getService(Context.POWER_SERVICE));
87        mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
88    }
89
90    /**
91     * After a radio technology change, e.g. from CDMA to GSM or vice versa,
92     * the Context of the Ringer has to be updated. This is done by that function.
93     *
94     * @parameter Phone, the new active phone for the appropriate radio
95     * technology
96     */
97    void updateRingerContextAfterRadioTechnologyChange(Phone phone) {
98        if(DBG) Log.d(LOG_TAG, "updateRingerContextAfterRadioTechnologyChange...");
99        mContext = phone.getContext();
100    }
101
102    /**
103     * @return true if we're playing a ringtone and/or vibrating
104     *     to indicate that there's an incoming call.
105     *     ("Ringing" here is used in the general sense.  If you literally
106     *     need to know if we're playing a ringtone or vibrating, use
107     *     isRingtonePlaying() or isVibrating() instead.)
108     *
109     * @see isVibrating
110     * @see isRingtonePlaying
111     */
112    boolean isRinging() {
113        synchronized (this) {
114            return (isRingtonePlaying() || isVibrating());
115        }
116    }
117
118    /**
119     * @return true if the ringtone is playing
120     * @see isVibrating
121     * @see isRinging
122     */
123    private boolean isRingtonePlaying() {
124        synchronized (this) {
125            return (mRingtone != null && mRingtone.isPlaying()) ||
126                    (mRingHandler != null && mRingHandler.hasMessages(PLAY_RING_ONCE));
127        }
128    }
129
130    /**
131     * @return true if we're vibrating in response to an incoming call
132     * @see isVibrating
133     * @see isRinging
134     */
135    private boolean isVibrating() {
136        synchronized (this) {
137            return (mVibratorThread != null);
138        }
139    }
140
141    /**
142     * Starts the ringtone and/or vibrator
143     */
144    void ring() {
145        if (DBG) log("ring()...");
146
147        synchronized (this) {
148            try {
149                if (PhoneApp.getInstance().showBluetoothIndication()) {
150                    mPowerManager.setAttentionLight(true, 0x000000ff);
151		} else {
152                    mPowerManager.setAttentionLight(true, 0x00ffffff);
153		}
154            } catch (RemoteException ex) {
155                // the other end of this binder call is in the system process.
156            }
157
158            if (shouldVibrate() && mVibratorThread == null) {
159                mContinueVibrating = true;
160                mVibratorThread = new VibratorThread();
161                if (DBG) log("- starting vibrator...");
162                mVibratorThread.start();
163            }
164            AudioManager audioManager =
165                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
166
167            if (audioManager.getStreamVolume(AudioManager.STREAM_RING) == 0) {
168                if (DBG) log("skipping ring because volume is zero");
169                return;
170            }
171
172            makeLooper();
173            if (mFirstRingEventTime < 0) {
174                mFirstRingEventTime = SystemClock.elapsedRealtime();
175                mRingHandler.sendEmptyMessage(PLAY_RING_ONCE);
176            } else {
177                // For repeat rings, figure out by how much to delay
178                // the ring so that it happens the correct amount of
179                // time after the previous ring
180                if (mFirstRingStartTime > 0) {
181                    // Delay subsequent rings by the delta between event
182                    // and play time of the first ring
183                    if (DBG) {
184                        log("delaying ring by " + (mFirstRingStartTime - mFirstRingEventTime));
185                    }
186                    mRingHandler.sendEmptyMessageDelayed(PLAY_RING_ONCE,
187                            mFirstRingStartTime - mFirstRingEventTime);
188                } else {
189                    // We've gotten two ring events so far, but the ring
190                    // still hasn't started. Reset the event time to the
191                    // time of this event to maintain correct spacing.
192                    mFirstRingEventTime = SystemClock.elapsedRealtime();
193                }
194            }
195        }
196    }
197
198    boolean shouldVibrate() {
199        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
200        return !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT);
201    }
202
203    /**
204     * Stops the ringtone and/or vibrator if any of these are actually
205     * ringing/vibrating.
206     */
207    void stopRing() {
208        synchronized (this) {
209            if (DBG) log("stopRing()...");
210
211            try {
212                mPowerManager.setAttentionLight(false, 0x00000000);
213            } catch (RemoteException ex) {
214                // the other end of this binder call is in the system process.
215            }
216
217            if (mRingHandler != null) {
218                mRingHandler.removeCallbacksAndMessages(null);
219                Message msg = mRingHandler.obtainMessage(STOP_RING);
220                msg.obj = mRingtone;
221                mRingHandler.sendMessage(msg);
222                PhoneUtils.setAudioMode();
223                mRingThread = null;
224                mRingHandler = null;
225                mRingtone = null;
226                mFirstRingEventTime = -1;
227                mFirstRingStartTime = -1;
228            } else {
229                if (DBG) log("- stopRing: null mRingHandler!");
230            }
231
232            if (mVibratorThread != null) {
233                if (DBG) log("- stopRing: cleaning up vibrator thread...");
234                mContinueVibrating = false;
235                mVibratorThread = null;
236            }
237            // Also immediately cancel any vibration in progress.
238            mVibrator.cancel();
239        }
240    }
241
242    private class VibratorThread extends Thread {
243        public void run() {
244            while (mContinueVibrating) {
245                mVibrator.vibrate(VIBRATE_LENGTH);
246                SystemClock.sleep(VIBRATE_LENGTH + PAUSE_LENGTH);
247            }
248        }
249    }
250    private class Worker implements Runnable {
251        private final Object mLock = new Object();
252        private Looper mLooper;
253
254        Worker(String name) {
255            Thread t = new Thread(null, this, name);
256            t.start();
257            synchronized (mLock) {
258                while (mLooper == null) {
259                    try {
260                        mLock.wait();
261                    } catch (InterruptedException ex) {
262                    }
263                }
264            }
265        }
266
267        public Looper getLooper() {
268            return mLooper;
269        }
270
271        public void run() {
272            synchronized (mLock) {
273                Looper.prepare();
274                mLooper = Looper.myLooper();
275                mLock.notifyAll();
276            }
277            Looper.loop();
278        }
279
280        public void quit() {
281            mLooper.quit();
282        }
283    }
284
285    /**
286     * Sets the ringtone uri in preparation for ringtone creation
287     * in makeLooper().  This uri is defaulted to the phone-wide
288     * default ringtone.
289     */
290    void setCustomRingtoneUri (Uri uri) {
291        if (uri != null) {
292            mCustomRingtoneUri = uri;
293        }
294    }
295
296    private void makeLooper() {
297        if (mRingThread == null) {
298            mRingThread = new Worker("ringer");
299            mRingHandler = new Handler(mRingThread.getLooper()) {
300                @Override
301                public void handleMessage(Message msg) {
302                    Ringtone r = null;
303                    switch (msg.what) {
304                        case PLAY_RING_ONCE:
305                            if (DBG) log("mRingHandler: PLAY_RING_ONCE...");
306                            if (mRingtone == null && !hasMessages(STOP_RING)) {
307                                // create the ringtone with the uri
308                                if (DBG) log("creating ringtone: " + mCustomRingtoneUri);
309                                r = RingtoneManager.getRingtone(mContext, mCustomRingtoneUri);
310                                synchronized (Ringer.this) {
311                                    if (!hasMessages(STOP_RING)) {
312                                        mRingtone = r;
313                                    }
314                                }
315                            }
316                            r = mRingtone;
317                            if (r != null && !hasMessages(STOP_RING) && !r.isPlaying()) {
318                                PhoneUtils.setAudioMode();
319                                r.play();
320                                synchronized (Ringer.this) {
321                                    if (mFirstRingStartTime < 0) {
322                                        mFirstRingStartTime = SystemClock.elapsedRealtime();
323                                    }
324                                }
325                            }
326                            break;
327                        case STOP_RING:
328                            if (DBG) log("mRingHandler: STOP_RING...");
329                            r = (Ringtone) msg.obj;
330                            if (r != null) {
331                                r.stop();
332                            } else {
333                                if (DBG) log("- STOP_RING with null ringtone!  msg = " + msg);
334                            }
335                            getLooper().quit();
336                            break;
337                    }
338                }
339            };
340        }
341    }
342
343    private static void log(String msg) {
344        Log.d(LOG_TAG, msg);
345    }
346}
347