NotificationMgr.java revision d649d4dcc7832139e6237cc2ffebf9680c7e2438
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.app.Notification;
20import android.app.NotificationManager;
21import android.app.PendingIntent;
22import android.app.StatusBarManager;
23import android.content.AsyncQueryHandler;
24import android.content.ComponentName;
25import android.content.ContentResolver;
26import android.content.ContentUris;
27import android.content.Context;
28import android.content.Intent;
29import android.content.SharedPreferences;
30import android.database.Cursor;
31import android.graphics.Bitmap;
32import android.graphics.drawable.BitmapDrawable;
33import android.graphics.drawable.Drawable;
34import android.media.AudioManager;
35import android.net.Uri;
36import android.os.PowerManager;
37import android.os.SystemClock;
38import android.os.SystemProperties;
39import android.preference.PreferenceManager;
40import android.provider.CallLog.Calls;
41import android.provider.ContactsContract.Contacts;
42import android.provider.ContactsContract.PhoneLookup;
43import android.telephony.PhoneNumberUtils;
44import android.telephony.ServiceState;
45import android.text.TextUtils;
46import android.util.Log;
47import android.widget.RemoteViews;
48import android.widget.Toast;
49
50import com.android.internal.telephony.Call;
51import com.android.internal.telephony.CallManager;
52import com.android.internal.telephony.CallerInfo;
53import com.android.internal.telephony.CallerInfoAsyncQuery;
54import com.android.internal.telephony.Connection;
55import com.android.internal.telephony.Phone;
56import com.android.internal.telephony.PhoneBase;
57import com.android.internal.telephony.TelephonyCapabilities;
58
59/**
60 * NotificationManager-related utility code for the Phone app.
61 *
62 * This is a singleton object which acts as the interface to the
63 * framework's NotificationManager, and is used to display status bar
64 * icons and control other status bar-related behavior.
65 *
66 * @see PhoneApp.notificationMgr
67 */
68public class NotificationMgr implements CallerInfoAsyncQuery.OnQueryCompleteListener{
69    private static final String LOG_TAG = "NotificationMgr";
70    private static final boolean DBG =
71            (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
72
73    private static final String[] CALL_LOG_PROJECTION = new String[] {
74        Calls._ID,
75        Calls.NUMBER,
76        Calls.DATE,
77        Calls.DURATION,
78        Calls.TYPE,
79    };
80
81    // notification types
82    static final int MISSED_CALL_NOTIFICATION = 1;
83    static final int IN_CALL_NOTIFICATION = 2;
84    static final int MMI_NOTIFICATION = 3;
85    static final int NETWORK_SELECTION_NOTIFICATION = 4;
86    static final int VOICEMAIL_NOTIFICATION = 5;
87    static final int CALL_FORWARD_NOTIFICATION = 6;
88    static final int DATA_DISCONNECTED_ROAMING_NOTIFICATION = 7;
89    static final int SELECTED_OPERATOR_FAIL_NOTIFICATION = 8;
90
91    /** The singleton NotificationMgr instance. */
92    private static NotificationMgr sInstance;
93
94    private PhoneApp mApp;
95    private Phone mPhone;
96    private CallManager mCM;
97
98    private Context mContext;
99    private NotificationManager mNotificationManager;
100    private StatusBarManager mStatusBarManager;
101    private PowerManager mPowerManager;
102    private Toast mToast;
103    private boolean mShowingSpeakerphoneIcon;
104    private boolean mShowingMuteIcon;
105
106    public StatusBarHelper statusBarHelper;
107
108    // used to track the missed call counter, default to 0.
109    private int mNumberMissedCalls = 0;
110
111    // Currently-displayed resource IDs for some status bar icons (or zero
112    // if no notification is active):
113    private int mInCallResId;
114
115    // used to track the notification of selected network unavailable
116    private boolean mSelectedUnavailableNotify = false;
117
118    // Retry params for the getVoiceMailNumber() call; see updateMwi().
119    private static final int MAX_VM_NUMBER_RETRIES = 5;
120    private static final int VM_NUMBER_RETRY_DELAY_MILLIS = 10000;
121    private int mVmNumberRetriesRemaining = MAX_VM_NUMBER_RETRIES;
122
123    // Query used to look up caller-id info for the "call log" notification.
124    private QueryHandler mQueryHandler = null;
125    private static final int CALL_LOG_TOKEN = -1;
126    private static final int CONTACT_TOKEN = -2;
127
128    /**
129     * Private constructor (this is a singleton).
130     * @see init()
131     */
132    private NotificationMgr(PhoneApp app) {
133        mApp = app;
134        mContext = app;
135        mNotificationManager =
136                (NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE);
137        mStatusBarManager =
138                (StatusBarManager) app.getSystemService(Context.STATUS_BAR_SERVICE);
139        mPowerManager =
140                (PowerManager) app.getSystemService(Context.POWER_SERVICE);
141        mPhone = app.phone;  // TODO: better style to use mCM.getDefaultPhone() everywhere instead
142        mCM = app.mCM;
143        statusBarHelper = new StatusBarHelper();
144    }
145
146    /**
147     * Initialize the singleton NotificationMgr instance.
148     *
149     * This is only done once, at startup, from PhoneApp.onCreate().
150     * From then on, the NotificationMgr instance is available via the
151     * PhoneApp's public "notificationMgr" field, which is why there's no
152     * getInstance() method here.
153     */
154    /* package */ static NotificationMgr init(PhoneApp app) {
155        synchronized (NotificationMgr.class) {
156            if (sInstance == null) {
157                sInstance = new NotificationMgr(app);
158                // Update the notifications that need to be touched at startup.
159                sInstance.updateNotificationsAtStartup();
160            } else {
161                Log.wtf(LOG_TAG, "init() called multiple times!  sInstance = " + sInstance);
162            }
163            return sInstance;
164        }
165    }
166
167    /**
168     * Helper class that's a wrapper around the framework's
169     * StatusBarManager.disable() API.
170     *
171     * This class is used to control features like:
172     *
173     *   - Disabling the status bar "notification windowshade"
174     *     while the in-call UI is up
175     *
176     *   - Disabling notification alerts (audible or vibrating)
177     *     while a phone call is active
178     *
179     *   - Disabling navigation via the system bar (the "soft buttons" at
180     *     the bottom of the screen on devices with no hard buttons)
181     *
182     * We control these features through a single point of control to make
183     * sure that the various StatusBarManager.disable() calls don't
184     * interfere with each other.
185     */
186    public class StatusBarHelper {
187        // Current desired state of status bar / system bar behavior
188        private boolean mIsNotificationEnabled = true;
189        private boolean mIsExpandedViewEnabled = true;
190        private boolean mIsSystemBarNavigationEnabled = true;
191
192        private StatusBarHelper () {
193        }
194
195        /**
196         * Enables or disables auditory / vibrational alerts.
197         *
198         * (We disable these any time a voice call is active, regardless
199         * of whether or not the in-call UI is visible.)
200         */
201        public void enableNotificationAlerts(boolean enable) {
202            if (mIsNotificationEnabled != enable) {
203                mIsNotificationEnabled = enable;
204                updateStatusBar();
205            }
206        }
207
208        /**
209         * Enables or disables the expanded view of the status bar
210         * (i.e. the ability to pull down the "notification windowshade").
211         *
212         * (This feature is disabled by the InCallScreen while the in-call
213         * UI is active.)
214         */
215        public void enableExpandedView(boolean enable) {
216            if (mIsExpandedViewEnabled != enable) {
217                mIsExpandedViewEnabled = enable;
218                updateStatusBar();
219            }
220        }
221
222        /**
223         * Enables or disables the navigation via the system bar (the
224         * "soft buttons" at the bottom of the screen)
225         *
226         * (This feature is disabled while an incoming call is ringing,
227         * because it's easy to accidentally touch the system bar while
228         * pulling the phone out of your pocket.)
229         */
230        public void enableSystemBarNavigation(boolean enable) {
231            if (mIsSystemBarNavigationEnabled != enable) {
232                mIsSystemBarNavigationEnabled = enable;
233                updateStatusBar();
234            }
235        }
236
237        /**
238         * Updates the status bar to reflect the current desired state.
239         */
240        private void updateStatusBar() {
241            int state = StatusBarManager.DISABLE_NONE;
242
243            if (!mIsExpandedViewEnabled) {
244                state |= StatusBarManager.DISABLE_EXPAND;
245            }
246            if (!mIsNotificationEnabled) {
247                state |= StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
248            }
249            if (!mIsSystemBarNavigationEnabled) {
250                // Disable *all* possible navigation via the system bar.
251                state |= StatusBarManager.DISABLE_HOME;
252                state |= StatusBarManager.DISABLE_RECENT;
253                state |= StatusBarManager.DISABLE_BACK;
254            }
255
256            if (DBG) log("updateStatusBar: state = 0x" + Integer.toHexString(state));
257            mStatusBarManager.disable(state);
258        }
259    }
260
261    /**
262     * Makes sure phone-related notifications are up to date on a
263     * freshly-booted device.
264     */
265    private void updateNotificationsAtStartup() {
266        if (DBG) log("updateNotificationsAtStartup()...");
267
268        // instantiate query handler
269        mQueryHandler = new QueryHandler(mContext.getContentResolver());
270
271        // setup query spec, look for all Missed calls that are new.
272        StringBuilder where = new StringBuilder("type=");
273        where.append(Calls.MISSED_TYPE);
274        where.append(" AND new=1");
275
276        // start the query
277        if (DBG) log("- start call log query...");
278        mQueryHandler.startQuery(CALL_LOG_TOKEN, null, Calls.CONTENT_URI,  CALL_LOG_PROJECTION,
279                where.toString(), null, Calls.DEFAULT_SORT_ORDER);
280
281        // Update (or cancel) the in-call notification
282        if (DBG) log("- updating in-call notification at startup...");
283        updateInCallNotification();
284
285        // Depend on android.app.StatusBarManager to be set to
286        // disable(DISABLE_NONE) upon startup.  This will be the
287        // case even if the phone app crashes.
288    }
289
290    /** The projection to use when querying the phones table */
291    static final String[] PHONES_PROJECTION = new String[] {
292        PhoneLookup.NUMBER,
293        PhoneLookup.DISPLAY_NAME
294    };
295
296    /**
297     * Class used to run asynchronous queries to re-populate
298     * the notifications we care about.
299     */
300    private class QueryHandler extends AsyncQueryHandler {
301
302        /**
303         * Used to store relevant fields for the Missed Call
304         * notifications.
305         */
306        private class NotificationInfo {
307            public String name;
308            public String number;
309            public String label;
310            public long date;
311        }
312
313        public QueryHandler(ContentResolver cr) {
314            super(cr);
315        }
316
317        /**
318         * Handles the query results.  There are really 2 steps to this,
319         * similar to what happens in CallLogActivity.
320         *  1. Find the list of missed calls
321         *  2. For each call, run a query to retrieve the caller's name.
322         */
323        @Override
324        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
325            // TODO: it would be faster to use a join here, but for the purposes
326            // of this small record set, it should be ok.
327
328            // Note that CursorJoiner is not useable here because the number
329            // comparisons are not strictly equals; the comparisons happen in
330            // the SQL function PHONE_NUMBERS_EQUAL, which is not available for
331            // the CursorJoiner.
332
333            // Executing our own query is also feasible (with a join), but that
334            // will require some work (possibly destabilizing) in Contacts
335            // Provider.
336
337            // At this point, we will execute subqueries on each row just as
338            // CallLogActivity.java does.
339            switch (token) {
340                case CALL_LOG_TOKEN:
341                    if (DBG) log("call log query complete.");
342
343                    // initial call to retrieve the call list.
344                    if (cursor != null) {
345                        while (cursor.moveToNext()) {
346                            // for each call in the call log list, create
347                            // the notification object and query contacts
348                            NotificationInfo n = getNotificationInfo (cursor);
349
350                            if (DBG) log("query contacts for number: " + n.number);
351
352                            mQueryHandler.startQuery(CONTACT_TOKEN, n,
353                                    Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, n.number),
354                                    PHONES_PROJECTION, null, null, PhoneLookup.NUMBER);
355                        }
356
357                        if (DBG) log("closing call log cursor.");
358                        cursor.close();
359                    }
360                    break;
361                case CONTACT_TOKEN:
362                    if (DBG) log("contact query complete.");
363
364                    // subqueries to get the caller name.
365                    if ((cursor != null) && (cookie != null)){
366                        NotificationInfo n = (NotificationInfo) cookie;
367
368                        if (cursor.moveToFirst()) {
369                            // we have contacts data, get the name.
370                            if (DBG) log("contact :" + n.name + " found for phone: " + n.number);
371                            n.name = cursor.getString(
372                                    cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
373                        }
374
375                        // send the notification
376                        if (DBG) log("sending notification.");
377                        notifyMissedCall(n.name, n.number, n.label, n.date);
378
379                        if (DBG) log("closing contact cursor.");
380                        cursor.close();
381                    }
382                    break;
383                default:
384            }
385        }
386
387        /**
388         * Factory method to generate a NotificationInfo object given a
389         * cursor from the call log table.
390         */
391        private final NotificationInfo getNotificationInfo(Cursor cursor) {
392            NotificationInfo n = new NotificationInfo();
393            n.name = null;
394            n.number = cursor.getString(cursor.getColumnIndexOrThrow(Calls.NUMBER));
395            n.label = cursor.getString(cursor.getColumnIndexOrThrow(Calls.TYPE));
396            n.date = cursor.getLong(cursor.getColumnIndexOrThrow(Calls.DATE));
397
398            // make sure we update the number depending upon saved values in
399            // CallLog.addCall().  If either special values for unknown or
400            // private number are detected, we need to hand off the message
401            // to the missed call notification.
402            if ( (n.number.equals(CallerInfo.UNKNOWN_NUMBER)) ||
403                 (n.number.equals(CallerInfo.PRIVATE_NUMBER)) ||
404                 (n.number.equals(CallerInfo.PAYPHONE_NUMBER)) ) {
405                n.number = null;
406            }
407
408            if (DBG) log("NotificationInfo constructed for number: " + n.number);
409
410            return n;
411        }
412    }
413
414    /**
415     * Configures a Notification to emit the blinky green message-waiting/
416     * missed-call signal.
417     */
418    private static void configureLedNotification(Notification note) {
419        note.flags |= Notification.FLAG_SHOW_LIGHTS;
420        note.defaults |= Notification.DEFAULT_LIGHTS;
421    }
422
423    /**
424     * Displays a notification about a missed call.
425     *
426     * @param nameOrNumber either the contact name, or the phone number if no contact
427     * @param label the label of the number if nameOrNumber is a name, null if it is a number
428     */
429    void notifyMissedCall(String name, String number, String label, long date) {
430        // When the user clicks this notification, we go to the call log.
431        final Intent callLogIntent = PhoneApp.createCallLogIntent();
432
433        // Never display the missed call notification on non-voice-capable
434        // devices, even if the device does somehow manage to get an
435        // incoming call.
436        if (!PhoneApp.sVoiceCapable) {
437            if (DBG) log("notifyMissedCall: non-voice-capable device, not posting notification");
438            return;
439        }
440
441        // title resource id
442        int titleResId;
443        // the text in the notification's line 1 and 2.
444        String expandedText, callName;
445
446        // increment number of missed calls.
447        mNumberMissedCalls++;
448
449        // get the name for the ticker text
450        // i.e. "Missed call from <caller name or number>"
451        if (name != null && TextUtils.isGraphic(name)) {
452            callName = name;
453        } else if (!TextUtils.isEmpty(number)){
454            callName = number;
455        } else {
456            // use "unknown" if the caller is unidentifiable.
457            callName = mContext.getString(R.string.unknown);
458        }
459
460        // display the first line of the notification:
461        // 1 missed call: call name
462        // more than 1 missed call: <number of calls> + "missed calls"
463        if (mNumberMissedCalls == 1) {
464            titleResId = R.string.notification_missedCallTitle;
465            expandedText = callName;
466        } else {
467            titleResId = R.string.notification_missedCallsTitle;
468            expandedText = mContext.getString(R.string.notification_missedCallsMsg,
469                    mNumberMissedCalls);
470        }
471
472        // make the notification
473        Notification note = new Notification(
474                android.R.drawable.stat_notify_missed_call, // icon
475                mContext.getString(R.string.notification_missedCallTicker, callName), // tickerText
476                date // when
477                );
478        note.setLatestEventInfo(mContext, mContext.getText(titleResId), expandedText,
479                PendingIntent.getActivity(mContext, 0, callLogIntent, 0));
480        note.flags |= Notification.FLAG_AUTO_CANCEL;
481        // This intent will be called when the notification is dismissed.
482        // It will take care of clearing the list of missed calls.
483        note.deleteIntent = createClearMissedCallsIntent();
484
485        configureLedNotification(note);
486        mNotificationManager.notify(MISSED_CALL_NOTIFICATION, note);
487    }
488
489    /** Returns an intent to be invoked when the missed call notification is cleared. */
490    private PendingIntent createClearMissedCallsIntent() {
491        Intent intent = new Intent(mContext, ClearMissedCallsService.class);
492        intent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS);
493        return PendingIntent.getService(mContext, 0, intent, 0);
494    }
495
496    /**
497     * Cancels the "missed call" notification.
498     *
499     * @see ITelephony.cancelMissedCallsNotification()
500     */
501    void cancelMissedCallNotification() {
502        // reset the number of missed calls to 0.
503        mNumberMissedCalls = 0;
504        mNotificationManager.cancel(MISSED_CALL_NOTIFICATION);
505    }
506
507    private void notifySpeakerphone() {
508        if (!mShowingSpeakerphoneIcon) {
509            mStatusBarManager.setIcon("speakerphone", android.R.drawable.stat_sys_speakerphone, 0,
510                    mContext.getString(R.string.accessibility_speakerphone_enabled));
511            mShowingSpeakerphoneIcon = true;
512        }
513    }
514
515    private void cancelSpeakerphone() {
516        if (mShowingSpeakerphoneIcon) {
517            mStatusBarManager.removeIcon("speakerphone");
518            mShowingSpeakerphoneIcon = false;
519        }
520    }
521
522    /**
523     * Shows or hides the "speakerphone" notification in the status bar,
524     * based on the actual current state of the speaker.
525     *
526     * If you already know the current speaker state (e.g. if you just
527     * called AudioManager.setSpeakerphoneOn() yourself) then you should
528     * directly call {@link #updateSpeakerNotification(boolean)} instead.
529     *
530     * (But note that the status bar icon is *never* shown while the in-call UI
531     * is active; it only appears if you bail out to some other activity.)
532     */
533    private void updateSpeakerNotification() {
534        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
535        boolean showNotification =
536                (mPhone.getState() == Phone.State.OFFHOOK) && audioManager.isSpeakerphoneOn();
537
538        if (DBG) log(showNotification
539                     ? "updateSpeakerNotification: speaker ON"
540                     : "updateSpeakerNotification: speaker OFF (or not offhook)");
541
542        updateSpeakerNotification(showNotification);
543    }
544
545    /**
546     * Shows or hides the "speakerphone" notification in the status bar.
547     *
548     * @param showNotification if true, call notifySpeakerphone();
549     *                         if false, call cancelSpeakerphone().
550     *
551     * Use {@link updateSpeakerNotification()} to update the status bar
552     * based on the actual current state of the speaker.
553     *
554     * (But note that the status bar icon is *never* shown while the in-call UI
555     * is active; it only appears if you bail out to some other activity.)
556     */
557    public void updateSpeakerNotification(boolean showNotification) {
558        if (DBG) log("updateSpeakerNotification(" + showNotification + ")...");
559
560        // Regardless of the value of the showNotification param, suppress
561        // the status bar icon if the the InCallScreen is the foreground
562        // activity, since the in-call UI already provides an onscreen
563        // indication of the speaker state.  (This reduces clutter in the
564        // status bar.)
565        if (mApp.isShowingCallScreen()) {
566            cancelSpeakerphone();
567            return;
568        }
569
570        if (showNotification) {
571            notifySpeakerphone();
572        } else {
573            cancelSpeakerphone();
574        }
575    }
576
577    private void notifyMute() {
578        if (!mShowingMuteIcon) {
579            mStatusBarManager.setIcon("mute", android.R.drawable.stat_notify_call_mute, 0,
580                    mContext.getString(R.string.accessibility_call_muted));
581            mShowingMuteIcon = true;
582        }
583    }
584
585    private void cancelMute() {
586        if (mShowingMuteIcon) {
587            mStatusBarManager.removeIcon("mute");
588            mShowingMuteIcon = false;
589        }
590    }
591
592    /**
593     * Shows or hides the "mute" notification in the status bar,
594     * based on the current mute state of the Phone.
595     *
596     * (But note that the status bar icon is *never* shown while the in-call UI
597     * is active; it only appears if you bail out to some other activity.)
598     */
599    void updateMuteNotification() {
600        // Suppress the status bar icon if the the InCallScreen is the
601        // foreground activity, since the in-call UI already provides an
602        // onscreen indication of the mute state.  (This reduces clutter
603        // in the status bar.)
604        if (mApp.isShowingCallScreen()) {
605            cancelMute();
606            return;
607        }
608
609        if ((mCM.getState() == Phone.State.OFFHOOK) && PhoneUtils.getMute()) {
610            if (DBG) log("updateMuteNotification: MUTED");
611            notifyMute();
612        } else {
613            if (DBG) log("updateMuteNotification: not muted (or not offhook)");
614            cancelMute();
615        }
616    }
617
618    /**
619     * Updates the phone app's status bar notification based on the
620     * current telephony state, or cancels the notification if the phone
621     * is totally idle.
622     *
623     * This method will never actually launch the incoming-call UI.
624     * (Use updateNotificationAndLaunchIncomingCallUi() for that.)
625     */
626    public void updateInCallNotification() {
627        // allowFullScreenIntent=false means *don't* allow the incoming
628        // call UI to be launched.
629        updateInCallNotification(false);
630    }
631
632    /**
633     * Updates the phone app's status bar notification *and* launches the
634     * incoming call UI in response to a new incoming call.
635     *
636     * This is just like updateInCallNotification(), with one exception:
637     * If an incoming call is ringing (or call-waiting), the notification
638     * will also include a "fullScreenIntent" that will cause the
639     * InCallScreen to be launched immediately, unless the current
640     * foreground activity is marked as "immersive".
641     *
642     * (This is the mechanism that actually brings up the incoming call UI
643     * when we receive a "new ringing connection" event from the telephony
644     * layer.)
645     *
646     * Watch out: this method should ONLY be called directly from the code
647     * path in CallNotifier that handles the "new ringing connection"
648     * event from the telephony layer.  All other places that update the
649     * in-call notification (like for phone state changes) should call
650     * updateInCallNotification() instead.  (This ensures that we don't
651     * end up launching the InCallScreen multiple times for a single
652     * incoming call, which could cause slow responsiveness and/or visible
653     * glitches.)
654     *
655     * Also note that this method is safe to call even if the phone isn't
656     * actually ringing (or, more likely, if an incoming call *was*
657     * ringing briefly but then disconnected).  In that case, we'll simply
658     * update or cancel the in-call notification based on the current
659     * phone state.
660     *
661     * @see #updateInCallNotification(boolean)
662     */
663    public void updateNotificationAndLaunchIncomingCallUi() {
664        // Set allowFullScreenIntent=true to indicate that we *should*
665        // launch the incoming call UI if necessary.
666        updateInCallNotification(true);
667    }
668
669    /**
670     * Helper method for updateInCallNotification() and
671     * updateNotificationAndLaunchIncomingCallUi(): Update the phone app's
672     * status bar notification based on the current telephony state, or
673     * cancels the notification if the phone is totally idle.
674     *
675     * @param allowFullScreenIntent If true, *and* an incoming call is
676     *   ringing, the notification will include a "fullScreenIntent"
677     *   pointing at the InCallScreen (which will cause the InCallScreen
678     *   to be launched.)
679     *   Watch out: This should be set to true *only* when directly
680     *   handling the "new ringing connection" event from the telephony
681     *   layer (see updateNotificationAndLaunchIncomingCallUi().)
682     */
683    private void updateInCallNotification(boolean allowFullScreenIntent) {
684        int resId;
685        if (DBG) log("updateInCallNotification(allowFullScreenIntent = "
686                     + allowFullScreenIntent + ")...");
687
688        // Never display the "ongoing call" notification on
689        // non-voice-capable devices, even if the phone is actually
690        // offhook (like during a non-interactive OTASP call.)
691        if (!PhoneApp.sVoiceCapable) {
692            if (DBG) log("- non-voice-capable device; suppressing notification.");
693            return;
694        }
695
696        // If the phone is idle, completely clean up all call-related
697        // notifications.
698        if (mCM.getState() == Phone.State.IDLE) {
699            cancelInCall();
700            cancelMute();
701            cancelSpeakerphone();
702            return;
703        }
704
705        final boolean hasRingingCall = mCM.hasActiveRingingCall();
706        final boolean hasActiveCall = mCM.hasActiveFgCall();
707        final boolean hasHoldingCall = mCM.hasActiveBgCall();
708        if (DBG) {
709            log("  - hasRingingCall = " + hasRingingCall);
710            log("  - hasActiveCall = " + hasActiveCall);
711            log("  - hasHoldingCall = " + hasHoldingCall);
712        }
713
714        // Suppress the in-call notification if the InCallScreen is the
715        // foreground activity, since it's already obvious that you're on a
716        // call.  (The status bar icon is needed only if you navigate *away*
717        // from the in-call UI.)
718        //
719        // Note: we should not use isShowingCallScreen() here, since it will
720        // return false when the screen turns off during user's on the InCallScreen,
721        // which will cause a brief flicker of the icon in the status bar when
722        // the screen turns back on (due to the prox sensor, for example) while
723        // still on the InCallScreen.
724        boolean suppressNotification = mApp.isShowingCallScreenForProximity();
725        // if (DBG) log("- suppressNotification: initial value: " + suppressNotification);
726
727        // ...except for a couple of cases where we *never* suppress the
728        // notification:
729        //
730        //   - If there's an incoming ringing call: always show the
731        //     notification, since the in-call notification is what actually
732        //     launches the incoming call UI in the first place (see
733        //     notification.fullScreenIntent below.)  This makes sure that we'll
734        //     correctly handle the case where a new incoming call comes in but
735        //     the InCallScreen is already in the foreground.
736        if (hasRingingCall) suppressNotification = false;
737
738        //   - If "voice privacy" mode is active: always show the notification,
739        //     since that's the only "voice privacy" indication we have.
740        boolean enhancedVoicePrivacy = mApp.notifier.getVoicePrivacyState();
741        // if (DBG) log("updateInCallNotification: enhancedVoicePrivacy = " + enhancedVoicePrivacy);
742        if (enhancedVoicePrivacy) suppressNotification = false;
743
744        if (suppressNotification) {
745            if (DBG) log("- suppressNotification = true; reducing clutter in status bar...");
746            cancelInCall();
747            // Suppress the mute and speaker status bar icons too
748            // (also to reduce clutter in the status bar.)
749            cancelSpeakerphone();
750            cancelMute();
751            return;
752        }
753
754        // Display the appropriate icon in the status bar,
755        // based on the current phone and/or bluetooth state.
756
757        if (hasRingingCall) {
758            // There's an incoming ringing call.
759            resId = R.drawable.stat_sys_phone_call;
760        } else if (!hasActiveCall && hasHoldingCall) {
761            // There's only one call, and it's on hold.
762            if (enhancedVoicePrivacy) {
763                resId = R.drawable.stat_sys_vp_phone_call_on_hold;
764            } else {
765                resId = R.drawable.stat_sys_phone_call_on_hold;
766            }
767        } else {
768            if (enhancedVoicePrivacy) {
769                resId = R.drawable.stat_sys_vp_phone_call;
770            } else {
771                resId = R.drawable.stat_sys_phone_call;
772            }
773        }
774
775        // Note we can't just bail out now if (resId == mInCallResId),
776        // since even if the status icon hasn't changed, some *other*
777        // notification-related info may be different from the last time
778        // we were here (like the caller-id info of the foreground call,
779        // if the user swapped calls...)
780
781        if (DBG) log("- Updating status bar icon: resId = " + resId);
782        mInCallResId = resId;
783
784        // Even if both lines are in use, we only show a single item in
785        // the expanded Notifications UI.  It's labeled "Ongoing call"
786        // (or "On hold" if there's only one call, and it's on hold.)
787        // Also, we don't have room to display caller-id info from two
788        // different calls.  So if both lines are in use, display info
789        // from the foreground call.  And if there's a ringing call,
790        // display that regardless of the state of the other calls.
791
792        Call currentCall;
793        if (hasRingingCall) {
794            currentCall = mCM.getFirstActiveRingingCall();
795        } else if (hasActiveCall) {
796            currentCall = mCM.getActiveFgCall();
797        } else {
798            currentCall = mCM.getFirstActiveBgCall();
799        }
800        Connection currentConn = currentCall.getEarliestConnection();
801
802        final Notification.Builder builder = new Notification.Builder(mContext);
803        builder.setSmallIcon(mInCallResId).setOngoing(true);
804
805        // PendingIntent that can be used to launch the InCallScreen.  The
806        // system fires off this intent if the user pulls down the windowshade
807        // and clicks the notification's expanded view.  It's also used to
808        // launch the InCallScreen immediately when when there's an incoming
809        // call (see the "fullScreenIntent" field below).
810        PendingIntent inCallPendingIntent =
811                PendingIntent.getActivity(mContext, 0,
812                                          PhoneApp.createInCallIntent(), 0);
813        builder.setContentIntent(inCallPendingIntent);
814
815        // Update icon on the left of the notification.
816        // - If it is directly available from CallerInfo, we'll just use that.
817        // - If it is not, use the same icon as in the status bar.
818        CallerInfo callerInfo = null;
819        if (currentConn != null) {
820            Object o = currentConn.getUserData();
821            if (o instanceof CallerInfo) {
822                callerInfo = (CallerInfo) o;
823            } else if (o instanceof PhoneUtils.CallerInfoToken) {
824                callerInfo = ((PhoneUtils.CallerInfoToken) o).currentInfo;
825            } else {
826                Log.w(LOG_TAG, "CallerInfo isn't available while Call object is available.");
827            }
828        }
829        boolean largeIconWasSet = false;
830        if (callerInfo != null) {
831            // In most cases, the user will see the notification after CallerInfo is already
832            // available, and the Drawable coming from ContactProvider will be BitmapDrawable.
833            // So, we can just rely on setImageViewBitmap() for most of the cases.
834            if (callerInfo.isCachedPhotoCurrent) {
835                if (callerInfo.cachedPhoto instanceof BitmapDrawable) {
836                    if (DBG) log("- BitmapDrawable found for large icon");
837                    Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap();
838                    builder.setLargeIcon(bitmap);
839                    largeIconWasSet = true;
840                } else {
841                    if (DBG) {
842                        log("- Drawable was found but it wasn't BitmapDrawable ("
843                                + callerInfo.cachedPhoto + "). Ignore it.");
844                    }
845                }
846            }
847
848            if (!largeIconWasSet && callerInfo.photoResource > 0) {
849                if (DBG) {
850                    log("- BitmapDrawable nor person Id not found for large icon."
851                            + " Use photoResource: " + callerInfo.photoResource);
852                }
853                Drawable drawable =
854                        mContext.getResources().getDrawable(callerInfo.photoResource);
855                if (drawable instanceof BitmapDrawable) {
856                    Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap();
857                    builder.setLargeIcon(bitmap);
858                    largeIconWasSet = true;
859                } else {
860                    if (DBG) {
861                        log("- PhotoResource was found but it didn't return BitmapDrawable."
862                                + " Ignore it");
863                    }
864                }
865            }
866        } else {
867            if (DBG) log("- CallerInfo not found. Use the same icon as in the status bar.");
868        }
869
870        // Failed to fetch Bitmap.
871        if (!largeIconWasSet && DBG) {
872            log("- No useful Bitmap was found for the photo."
873                    + " Use the same icon as in the status bar.");
874        }
875
876        // If the connection is valid, then build what we need for the
877        // content text of notification, and start the chronometer.
878        // Otherwise, don't bother and just stick with content title.
879        if (currentConn != null) {
880            if (DBG) log("- Updating context text and chronometer.");
881            if (hasRingingCall) {
882                // Incoming call is ringing.
883                builder.setContentText(mContext.getString(R.string.notification_incoming_call));
884                builder.setUsesChronometer(false);
885            } else if (hasHoldingCall && !hasActiveCall) {
886                // Only one call, and it's on hold.
887                builder.setContentText(mContext.getString(R.string.notification_on_hold));
888                builder.setUsesChronometer(false);
889            } else {
890                // We show the elapsed time of the current call using Chronometer.
891                builder.setUsesChronometer(true);
892
893                // Determine the "start time" of the current connection.
894                //   We can't use currentConn.getConnectTime(), because (1) that's
895                // in the currentTimeMillis() time base, and (2) it's zero when
896                // the phone first goes off hook, since the getConnectTime counter
897                // doesn't start until the DIALING -> ACTIVE transition.
898                //   Instead we start with the current connection's duration,
899                // and translate that into the elapsedRealtime() timebase.
900                long callDurationMsec = currentConn.getDurationMillis();
901                builder.setWhen(System.currentTimeMillis() - callDurationMsec);
902                builder.setContentText(mContext.getString(R.string.notification_ongoing_call));
903            }
904        } else if (DBG) {
905            Log.w(LOG_TAG, "updateInCallNotification: null connection, can't set exp view line 1.");
906        }
907
908        // display conference call string if this call is a conference
909        // call, otherwise display the connection information.
910
911        // Line 2 of the expanded view (smaller text).  This is usually a
912        // contact name or phone number.
913        String expandedViewLine2 = "";
914        // TODO: it may not make sense for every point to make separate
915        // checks for isConferenceCall, so we need to think about
916        // possibly including this in startGetCallerInfo or some other
917        // common point.
918        if (PhoneUtils.isConferenceCall(currentCall)) {
919            // if this is a conference call, just use that as the caller name.
920            expandedViewLine2 = mContext.getString(R.string.card_title_conf_call);
921        } else {
922            // If necessary, start asynchronous query to do the caller-id lookup.
923            PhoneUtils.CallerInfoToken cit =
924                PhoneUtils.startGetCallerInfo(mContext, currentCall, this, this);
925            expandedViewLine2 = PhoneUtils.getCompactNameFromCallerInfo(cit.currentInfo, mContext);
926            // Note: For an incoming call, the very first time we get here we
927            // won't have a contact name yet, since we only just started the
928            // caller-id query.  So expandedViewLine2 will start off as a raw
929            // phone number, but we'll update it very quickly when the query
930            // completes (see onQueryComplete() below.)
931        }
932
933        if (DBG) log("- Updating expanded view: line 2 '" + /*expandedViewLine2*/ "xxxxxxx" + "'");
934        builder.setContentTitle(expandedViewLine2);
935
936        // TODO: We also need to *update* this notification in some cases,
937        // like when a call ends on one line but the other is still in use
938        // (ie. make sure the caller info here corresponds to the active
939        // line), and maybe even when the user swaps calls (ie. if we only
940        // show info here for the "current active call".)
941
942        // Activate a couple of special Notification features if an
943        // incoming call is ringing:
944        if (hasRingingCall) {
945            if (DBG) log("- Using hi-pri notification for ringing call!");
946
947            // This is a high-priority event that should be shown even if the
948            // status bar is hidden or if an immersive activity is running.
949            builder.setPriority(Notification.PRIORITY_HIGH);
950
951            // If an immersive activity is running, we have room for a single
952            // line of text in the small notification popup window.
953            // We use expandedViewLine2 for this (i.e. the name or number of
954            // the incoming caller), since that's more relevant than
955            // expandedViewLine1 (which is something generic like "Incoming
956            // call".)
957            builder.setTicker(expandedViewLine2);
958
959            if (allowFullScreenIntent) {
960                // Ok, we actually want to launch the incoming call
961                // UI at this point (in addition to simply posting a notification
962                // to the status bar).  Setting fullScreenIntent will cause
963                // the InCallScreen to be launched immediately *unless* the
964                // current foreground activity is marked as "immersive".
965                if (DBG) log("- Setting fullScreenIntent: " + inCallPendingIntent);
966                builder.setFullScreenIntent(inCallPendingIntent, true);
967
968                // Ugly hack alert:
969                //
970                // The NotificationManager has the (undocumented) behavior
971                // that it will *ignore* the fullScreenIntent field if you
972                // post a new Notification that matches the ID of one that's
973                // already active.  Unfortunately this is exactly what happens
974                // when you get an incoming call-waiting call:  the
975                // "ongoing call" notification is already visible, so the
976                // InCallScreen won't get launched in this case!
977                // (The result: if you bail out of the in-call UI while on a
978                // call and then get a call-waiting call, the incoming call UI
979                // won't come up automatically.)
980                //
981                // The workaround is to just notice this exact case (this is a
982                // call-waiting call *and* the InCallScreen is not in the
983                // foreground) and manually cancel the in-call notification
984                // before (re)posting it.
985                //
986                // TODO: there should be a cleaner way of avoiding this
987                // problem (see discussion in bug 3184149.)
988                Call ringingCall = mCM.getFirstActiveRingingCall();
989                if ((ringingCall.getState() == Call.State.WAITING) && !mApp.isShowingCallScreen()) {
990                    Log.i(LOG_TAG, "updateInCallNotification: call-waiting! force relaunch...");
991                    // Cancel the IN_CALL_NOTIFICATION immediately before
992                    // (re)posting it; this seems to force the
993                    // NotificationManager to launch the fullScreenIntent.
994                    mNotificationManager.cancel(IN_CALL_NOTIFICATION);
995                }
996            }
997        } else { // not ringing call
998            // TODO: use "if (DBG)" for this comment.
999            log("Will show \"hang-up\" action in the ongoing active call Notification");
1000            // TODO: use better asset.
1001            builder.addAction(R.drawable.ic_end_call,
1002                    mContext.getText(R.string.notification_action_end_call),
1003                    PhoneApp.createHangUpOngoingCallPendingIntent(mContext));
1004        }
1005
1006        Notification notification = builder.getNotification();
1007        if (DBG) log("Notifying IN_CALL_NOTIFICATION: " + notification);
1008        mNotificationManager.notify(IN_CALL_NOTIFICATION, notification);
1009
1010        // Finally, refresh the mute and speakerphone notifications (since
1011        // some phone state changes can indirectly affect the mute and/or
1012        // speaker state).
1013        updateSpeakerNotification();
1014        updateMuteNotification();
1015    }
1016
1017    /**
1018     * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
1019     * refreshes the contentView when called.
1020     */
1021    @Override
1022    public void onQueryComplete(int token, Object cookie, CallerInfo ci){
1023        if (DBG) log("CallerInfo query complete (for NotificationMgr), "
1024                     + "updating in-call notification..");
1025        if (DBG) log("- cookie: " + cookie);
1026        if (DBG) log("- ci: " + ci);
1027
1028        if (cookie == this) {
1029            // Ok, this is the caller-id query we fired off in
1030            // updateInCallNotification(), presumably when an incoming call
1031            // first appeared.  If the caller-id info matched any contacts,
1032            // compactName should now be a real person name rather than a raw
1033            // phone number:
1034            if (DBG) log("- compactName is now: "
1035                         + PhoneUtils.getCompactNameFromCallerInfo(ci, mContext));
1036
1037            // Now that our CallerInfo object has been fully filled-in,
1038            // refresh the in-call notification.
1039            if (DBG) log("- updating notification after query complete...");
1040            updateInCallNotification();
1041        } else {
1042            Log.w(LOG_TAG, "onQueryComplete: caller-id query from unknown source! "
1043                  + "cookie = " + cookie);
1044        }
1045    }
1046
1047    /**
1048     * Take down the in-call notification.
1049     * @see updateInCallNotification()
1050     */
1051    private void cancelInCall() {
1052        if (DBG) log("cancelInCall()...");
1053        mNotificationManager.cancel(IN_CALL_NOTIFICATION);
1054        mInCallResId = 0;
1055    }
1056
1057    /**
1058     * Completely take down the in-call notification *and* the mute/speaker
1059     * notifications as well, to indicate that the phone is now idle.
1060     */
1061    /* package */ void cancelCallInProgressNotifications() {
1062        if (DBG) log("cancelCallInProgressNotifications()...");
1063        if (mInCallResId == 0) {
1064            return;
1065        }
1066
1067        if (DBG) log("cancelCallInProgressNotifications: " + mInCallResId);
1068        cancelInCall();
1069        cancelMute();
1070        cancelSpeakerphone();
1071    }
1072
1073    /**
1074     * Updates the message waiting indicator (voicemail) notification.
1075     *
1076     * @param visible true if there are messages waiting
1077     */
1078    /* package */ void updateMwi(boolean visible) {
1079        if (DBG) log("updateMwi(): " + visible);
1080        if (visible) {
1081            int resId = android.R.drawable.stat_notify_voicemail;
1082
1083            // This Notification can get a lot fancier once we have more
1084            // information about the current voicemail messages.
1085            // (For example, the current voicemail system can't tell
1086            // us the caller-id or timestamp of a message, or tell us the
1087            // message count.)
1088
1089            // But for now, the UI is ultra-simple: if the MWI indication
1090            // is supposed to be visible, just show a single generic
1091            // notification.
1092
1093            String notificationTitle = mContext.getString(R.string.notification_voicemail_title);
1094            String vmNumber = mPhone.getVoiceMailNumber();
1095            if (DBG) log("- got vm number: '" + vmNumber + "'");
1096
1097            // Watch out: vmNumber may be null, for two possible reasons:
1098            //
1099            //   (1) This phone really has no voicemail number
1100            //
1101            //   (2) This phone *does* have a voicemail number, but
1102            //       the SIM isn't ready yet.
1103            //
1104            // Case (2) *does* happen in practice if you have voicemail
1105            // messages when the device first boots: we get an MWI
1106            // notification as soon as we register on the network, but the
1107            // SIM hasn't finished loading yet.
1108            //
1109            // So handle case (2) by retrying the lookup after a short
1110            // delay.
1111
1112            if ((vmNumber == null) && !mPhone.getIccRecordsLoaded()) {
1113                if (DBG) log("- Null vm number: SIM records not loaded (yet)...");
1114
1115                // TODO: rather than retrying after an arbitrary delay, it
1116                // would be cleaner to instead just wait for a
1117                // SIM_RECORDS_LOADED notification.
1118                // (Unfortunately right now there's no convenient way to
1119                // get that notification in phone app code.  We'd first
1120                // want to add a call like registerForSimRecordsLoaded()
1121                // to Phone.java and GSMPhone.java, and *then* we could
1122                // listen for that in the CallNotifier class.)
1123
1124                // Limit the number of retries (in case the SIM is broken
1125                // or missing and can *never* load successfully.)
1126                if (mVmNumberRetriesRemaining-- > 0) {
1127                    if (DBG) log("  - Retrying in " + VM_NUMBER_RETRY_DELAY_MILLIS + " msec...");
1128                    mApp.notifier.sendMwiChangedDelayed(VM_NUMBER_RETRY_DELAY_MILLIS);
1129                    return;
1130                } else {
1131                    Log.w(LOG_TAG, "NotificationMgr.updateMwi: getVoiceMailNumber() failed after "
1132                          + MAX_VM_NUMBER_RETRIES + " retries; giving up.");
1133                    // ...and continue with vmNumber==null, just as if the
1134                    // phone had no VM number set up in the first place.
1135                }
1136            }
1137
1138            if (TelephonyCapabilities.supportsVoiceMessageCount(mPhone)) {
1139                int vmCount = mPhone.getVoiceMessageCount();
1140                String titleFormat = mContext.getString(R.string.notification_voicemail_title_count);
1141                notificationTitle = String.format(titleFormat, vmCount);
1142            }
1143
1144            String notificationText;
1145            if (TextUtils.isEmpty(vmNumber)) {
1146                notificationText = mContext.getString(
1147                        R.string.notification_voicemail_no_vm_number);
1148            } else {
1149                notificationText = String.format(
1150                        mContext.getString(R.string.notification_voicemail_text_format),
1151                        PhoneNumberUtils.formatNumber(vmNumber));
1152            }
1153
1154            Intent intent = new Intent(Intent.ACTION_CALL,
1155                    Uri.fromParts(Constants.SCHEME_VOICEMAIL, "", null));
1156            PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
1157
1158            Notification notification = new Notification(
1159                    resId,  // icon
1160                    null, // tickerText
1161                    System.currentTimeMillis()  // Show the time the MWI notification came in,
1162                                                // since we don't know the actual time of the
1163                                                // most recent voicemail message
1164                    );
1165            notification.setLatestEventInfo(
1166                    mContext,  // context
1167                    notificationTitle,  // contentTitle
1168                    notificationText,  // contentText
1169                    pendingIntent  // contentIntent
1170                    );
1171            notification.defaults |= Notification.DEFAULT_SOUND;
1172
1173            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
1174            String vibrateWhen = prefs.getString(
1175                    CallFeaturesSetting.BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY, "never");
1176            boolean vibrateAlways = vibrateWhen.equals("always");
1177            boolean vibrateSilent = vibrateWhen.equals("silent");
1178            AudioManager audioManager =
1179                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1180            boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;
1181            if (vibrateAlways || (vibrateSilent && nowSilent)) {
1182                notification.defaults |= Notification.DEFAULT_VIBRATE;
1183            }
1184
1185            notification.flags |= Notification.FLAG_NO_CLEAR;
1186            configureLedNotification(notification);
1187            mNotificationManager.notify(VOICEMAIL_NOTIFICATION, notification);
1188        } else {
1189            mNotificationManager.cancel(VOICEMAIL_NOTIFICATION);
1190        }
1191    }
1192
1193    /**
1194     * Updates the message call forwarding indicator notification.
1195     *
1196     * @param visible true if there are messages waiting
1197     */
1198    /* package */ void updateCfi(boolean visible) {
1199        if (DBG) log("updateCfi(): " + visible);
1200        if (visible) {
1201            // If Unconditional Call Forwarding (forward all calls) for VOICE
1202            // is enabled, just show a notification.  We'll default to expanded
1203            // view for now, so the there is less confusion about the icon.  If
1204            // it is deemed too weird to have CF indications as expanded views,
1205            // then we'll flip the flag back.
1206
1207            // TODO: We may want to take a look to see if the notification can
1208            // display the target to forward calls to.  This will require some
1209            // effort though, since there are multiple layers of messages that
1210            // will need to propagate that information.
1211
1212            Notification notification;
1213            final boolean showExpandedNotification = true;
1214            if (showExpandedNotification) {
1215                Intent intent = new Intent(Intent.ACTION_MAIN);
1216                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1217                intent.setClassName("com.android.phone",
1218                        "com.android.phone.CallFeaturesSetting");
1219
1220                notification = new Notification(
1221                        R.drawable.stat_sys_phone_call_forward,  // icon
1222                        null, // tickerText
1223                        0); // The "timestamp" of this notification is meaningless;
1224                            // we only care about whether CFI is currently on or not.
1225                notification.setLatestEventInfo(
1226                        mContext, // context
1227                        mContext.getString(R.string.labelCF), // expandedTitle
1228                        mContext.getString(R.string.sum_cfu_enabled_indicator), // expandedText
1229                        PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent
1230            } else {
1231                notification = new Notification(
1232                        R.drawable.stat_sys_phone_call_forward,  // icon
1233                        null,  // tickerText
1234                        System.currentTimeMillis()  // when
1235                        );
1236            }
1237
1238            notification.flags |= Notification.FLAG_ONGOING_EVENT;  // also implies FLAG_NO_CLEAR
1239
1240            mNotificationManager.notify(
1241                    CALL_FORWARD_NOTIFICATION,
1242                    notification);
1243        } else {
1244            mNotificationManager.cancel(CALL_FORWARD_NOTIFICATION);
1245        }
1246    }
1247
1248    /**
1249     * Shows the "data disconnected due to roaming" notification, which
1250     * appears when you lose data connectivity because you're roaming and
1251     * you have the "data roaming" feature turned off.
1252     */
1253    /* package */ void showDataDisconnectedRoaming() {
1254        if (DBG) log("showDataDisconnectedRoaming()...");
1255
1256        // "Mobile network settings" screen / dialog
1257        Intent intent = new Intent(mContext,
1258                com.android.phone.MobileNetworkSettings.class);
1259
1260        Notification notification = new Notification(
1261                android.R.drawable.stat_sys_warning, // icon
1262                null, // tickerText
1263                System.currentTimeMillis());
1264        notification.setLatestEventInfo(
1265                mContext, // Context
1266                mContext.getString(R.string.roaming), // expandedTitle
1267                mContext.getString(R.string.roaming_reenable_message), // expandedText
1268                PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent
1269
1270        mNotificationManager.notify(
1271                DATA_DISCONNECTED_ROAMING_NOTIFICATION,
1272                notification);
1273    }
1274
1275    /**
1276     * Turns off the "data disconnected due to roaming" notification.
1277     */
1278    /* package */ void hideDataDisconnectedRoaming() {
1279        if (DBG) log("hideDataDisconnectedRoaming()...");
1280        mNotificationManager.cancel(DATA_DISCONNECTED_ROAMING_NOTIFICATION);
1281    }
1282
1283    /**
1284     * Display the network selection "no service" notification
1285     * @param operator is the numeric operator number
1286     */
1287    private void showNetworkSelection(String operator) {
1288        if (DBG) log("showNetworkSelection(" + operator + ")...");
1289
1290        String titleText = mContext.getString(
1291                R.string.notification_network_selection_title);
1292        String expandedText = mContext.getString(
1293                R.string.notification_network_selection_text, operator);
1294
1295        Notification notification = new Notification();
1296        notification.icon = android.R.drawable.stat_sys_warning;
1297        notification.when = 0;
1298        notification.flags = Notification.FLAG_ONGOING_EVENT;
1299        notification.tickerText = null;
1300
1301        // create the target network operators settings intent
1302        Intent intent = new Intent(Intent.ACTION_MAIN);
1303        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1304                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1305        // Use NetworkSetting to handle the selection intent
1306        intent.setComponent(new ComponentName("com.android.phone",
1307                "com.android.phone.NetworkSetting"));
1308        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
1309
1310        notification.setLatestEventInfo(mContext, titleText, expandedText, pi);
1311
1312        mNotificationManager.notify(SELECTED_OPERATOR_FAIL_NOTIFICATION, notification);
1313    }
1314
1315    /**
1316     * Turn off the network selection "no service" notification
1317     */
1318    private void cancelNetworkSelection() {
1319        if (DBG) log("cancelNetworkSelection()...");
1320        mNotificationManager.cancel(SELECTED_OPERATOR_FAIL_NOTIFICATION);
1321    }
1322
1323    /**
1324     * Update notification about no service of user selected operator
1325     *
1326     * @param serviceState Phone service state
1327     */
1328    void updateNetworkSelection(int serviceState) {
1329        if (TelephonyCapabilities.supportsNetworkSelection(mPhone)) {
1330            // get the shared preference of network_selection.
1331            // empty is auto mode, otherwise it is the operator alpha name
1332            // in case there is no operator name, check the operator numeric
1333            SharedPreferences sp =
1334                    PreferenceManager.getDefaultSharedPreferences(mContext);
1335            String networkSelection =
1336                    sp.getString(PhoneBase.NETWORK_SELECTION_NAME_KEY, "");
1337            if (TextUtils.isEmpty(networkSelection)) {
1338                networkSelection =
1339                        sp.getString(PhoneBase.NETWORK_SELECTION_KEY, "");
1340            }
1341
1342            if (DBG) log("updateNetworkSelection()..." + "state = " +
1343                    serviceState + " new network " + networkSelection);
1344
1345            if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
1346                    && !TextUtils.isEmpty(networkSelection)) {
1347                if (!mSelectedUnavailableNotify) {
1348                    showNetworkSelection(networkSelection);
1349                    mSelectedUnavailableNotify = true;
1350                }
1351            } else {
1352                if (mSelectedUnavailableNotify) {
1353                    cancelNetworkSelection();
1354                    mSelectedUnavailableNotify = false;
1355                }
1356            }
1357        }
1358    }
1359
1360    /* package */ void postTransientNotification(int notifyId, CharSequence msg) {
1361        if (mToast != null) {
1362            mToast.cancel();
1363        }
1364
1365        mToast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
1366        mToast.show();
1367    }
1368
1369    private void log(String msg) {
1370        Log.d(LOG_TAG, msg);
1371    }
1372}
1373