blob: 7771fa9f6559d34336b89579e023b7b07166c059 [file] [log] [blame]
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001/*
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.SystemProperties;
38import android.preference.PreferenceManager;
39import android.provider.CallLog.Calls;
40import android.provider.ContactsContract.Contacts;
41import android.provider.ContactsContract.PhoneLookup;
42import android.provider.Settings;
43import android.telephony.PhoneNumberUtils;
44import android.telephony.ServiceState;
Yorke Lee528bd1e2013-09-04 15:21:56 -070045import android.text.BidiFormatter;
46import android.text.TextDirectionHeuristics;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070047import android.text.TextUtils;
48import android.util.Log;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070049import android.widget.Toast;
50
51import com.android.internal.telephony.Call;
52import com.android.internal.telephony.CallManager;
53import com.android.internal.telephony.CallerInfo;
54import com.android.internal.telephony.CallerInfoAsyncQuery;
55import com.android.internal.telephony.Connection;
56import com.android.internal.telephony.Phone;
57import com.android.internal.telephony.PhoneBase;
58import com.android.internal.telephony.PhoneConstants;
59import com.android.internal.telephony.TelephonyCapabilities;
60
61/**
62 * NotificationManager-related utility code for the Phone app.
63 *
64 * This is a singleton object which acts as the interface to the
65 * framework's NotificationManager, and is used to display status bar
66 * icons and control other status bar-related behavior.
67 *
68 * @see PhoneGlobals.notificationMgr
69 */
Chiao Cheng312b9c92013-09-16 15:40:53 -070070public class NotificationMgr {
Santos Cordon7d4ddf62013-07-10 11:58:08 -070071 private static final String LOG_TAG = "NotificationMgr";
72 private static final boolean DBG =
73 (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
74 // Do not check in with VDBG = true, since that may write PII to the system log.
75 private static final boolean VDBG = false;
76
77 private static final String[] CALL_LOG_PROJECTION = new String[] {
78 Calls._ID,
79 Calls.NUMBER,
80 Calls.NUMBER_PRESENTATION,
81 Calls.DATE,
82 Calls.DURATION,
83 Calls.TYPE,
84 };
85
86 // notification types
87 static final int MISSED_CALL_NOTIFICATION = 1;
88 static final int IN_CALL_NOTIFICATION = 2;
89 static final int MMI_NOTIFICATION = 3;
90 static final int NETWORK_SELECTION_NOTIFICATION = 4;
91 static final int VOICEMAIL_NOTIFICATION = 5;
92 static final int CALL_FORWARD_NOTIFICATION = 6;
93 static final int DATA_DISCONNECTED_ROAMING_NOTIFICATION = 7;
94 static final int SELECTED_OPERATOR_FAIL_NOTIFICATION = 8;
95
96 /** The singleton NotificationMgr instance. */
97 private static NotificationMgr sInstance;
98
99 private PhoneGlobals mApp;
100 private Phone mPhone;
101 private CallManager mCM;
102
103 private Context mContext;
104 private NotificationManager mNotificationManager;
105 private StatusBarManager mStatusBarManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700106 private Toast mToast;
107 private boolean mShowingSpeakerphoneIcon;
108 private boolean mShowingMuteIcon;
109
110 public StatusBarHelper statusBarHelper;
111
112 // used to track the missed call counter, default to 0.
113 private int mNumberMissedCalls = 0;
114
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700115 // 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(PhoneGlobals 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);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700139 mPhone = app.phone; // TODO: better style to use mCM.getDefaultPhone() everywhere instead
140 mCM = app.mCM;
141 statusBarHelper = new StatusBarHelper();
142 }
143
144 /**
145 * Initialize the singleton NotificationMgr instance.
146 *
147 * This is only done once, at startup, from PhoneApp.onCreate().
148 * From then on, the NotificationMgr instance is available via the
149 * PhoneApp's public "notificationMgr" field, which is why there's no
150 * getInstance() method here.
151 */
152 /* package */ static NotificationMgr init(PhoneGlobals app) {
153 synchronized (NotificationMgr.class) {
154 if (sInstance == null) {
155 sInstance = new NotificationMgr(app);
156 // Update the notifications that need to be touched at startup.
157 sInstance.updateNotificationsAtStartup();
158 } else {
159 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
160 }
161 return sInstance;
162 }
163 }
164
165 /**
166 * Helper class that's a wrapper around the framework's
167 * StatusBarManager.disable() API.
168 *
169 * This class is used to control features like:
170 *
171 * - Disabling the status bar "notification windowshade"
172 * while the in-call UI is up
173 *
174 * - Disabling notification alerts (audible or vibrating)
175 * while a phone call is active
176 *
177 * - Disabling navigation via the system bar (the "soft buttons" at
178 * the bottom of the screen on devices with no hard buttons)
179 *
180 * We control these features through a single point of control to make
181 * sure that the various StatusBarManager.disable() calls don't
182 * interfere with each other.
183 */
184 public class StatusBarHelper {
185 // Current desired state of status bar / system bar behavior
186 private boolean mIsNotificationEnabled = true;
187 private boolean mIsExpandedViewEnabled = true;
188 private boolean mIsSystemBarNavigationEnabled = true;
189
190 private StatusBarHelper () {
191 }
192
193 /**
194 * Enables or disables auditory / vibrational alerts.
195 *
196 * (We disable these any time a voice call is active, regardless
197 * of whether or not the in-call UI is visible.)
198 */
199 public void enableNotificationAlerts(boolean enable) {
200 if (mIsNotificationEnabled != enable) {
201 mIsNotificationEnabled = enable;
202 updateStatusBar();
203 }
204 }
205
206 /**
207 * Enables or disables the expanded view of the status bar
208 * (i.e. the ability to pull down the "notification windowshade").
209 *
210 * (This feature is disabled by the InCallScreen while the in-call
211 * UI is active.)
212 */
213 public void enableExpandedView(boolean enable) {
214 if (mIsExpandedViewEnabled != enable) {
215 mIsExpandedViewEnabled = enable;
216 updateStatusBar();
217 }
218 }
219
220 /**
221 * Enables or disables the navigation via the system bar (the
222 * "soft buttons" at the bottom of the screen)
223 *
224 * (This feature is disabled while an incoming call is ringing,
225 * because it's easy to accidentally touch the system bar while
226 * pulling the phone out of your pocket.)
227 */
228 public void enableSystemBarNavigation(boolean enable) {
229 if (mIsSystemBarNavigationEnabled != enable) {
230 mIsSystemBarNavigationEnabled = enable;
231 updateStatusBar();
232 }
233 }
234
235 /**
236 * Updates the status bar to reflect the current desired state.
237 */
238 private void updateStatusBar() {
239 int state = StatusBarManager.DISABLE_NONE;
240
241 if (!mIsExpandedViewEnabled) {
242 state |= StatusBarManager.DISABLE_EXPAND;
243 }
244 if (!mIsNotificationEnabled) {
245 state |= StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
246 }
247 if (!mIsSystemBarNavigationEnabled) {
248 // Disable *all* possible navigation via the system bar.
249 state |= StatusBarManager.DISABLE_HOME;
250 state |= StatusBarManager.DISABLE_RECENT;
251 state |= StatusBarManager.DISABLE_BACK;
252 }
253
254 if (DBG) log("updateStatusBar: state = 0x" + Integer.toHexString(state));
255 mStatusBarManager.disable(state);
256 }
257 }
258
259 /**
260 * Makes sure phone-related notifications are up to date on a
261 * freshly-booted device.
262 */
263 private void updateNotificationsAtStartup() {
264 if (DBG) log("updateNotificationsAtStartup()...");
265
266 // instantiate query handler
267 mQueryHandler = new QueryHandler(mContext.getContentResolver());
268
269 // setup query spec, look for all Missed calls that are new.
270 StringBuilder where = new StringBuilder("type=");
271 where.append(Calls.MISSED_TYPE);
272 where.append(" AND new=1");
273
274 // start the query
275 if (DBG) log("- start call log query...");
276 mQueryHandler.startQuery(CALL_LOG_TOKEN, null, Calls.CONTENT_URI, CALL_LOG_PROJECTION,
277 where.toString(), null, Calls.DEFAULT_SORT_ORDER);
278
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700279 // Depend on android.app.StatusBarManager to be set to
280 // disable(DISABLE_NONE) upon startup. This will be the
281 // case even if the phone app crashes.
282 }
283
284 /** The projection to use when querying the phones table */
285 static final String[] PHONES_PROJECTION = new String[] {
286 PhoneLookup.NUMBER,
287 PhoneLookup.DISPLAY_NAME,
288 PhoneLookup._ID
289 };
290
291 /**
292 * Class used to run asynchronous queries to re-populate the notifications we care about.
293 * There are really 3 steps to this:
294 * 1. Find the list of missed calls
295 * 2. For each call, run a query to retrieve the caller's name.
296 * 3. For each caller, try obtaining photo.
297 */
298 private class QueryHandler extends AsyncQueryHandler
299 implements ContactsAsyncHelper.OnImageLoadCompleteListener {
300
301 /**
302 * Used to store relevant fields for the Missed Call
303 * notifications.
304 */
305 private class NotificationInfo {
306 public String name;
307 public String number;
308 public int presentation;
309 /**
310 * Type of the call. {@link android.provider.CallLog.Calls#INCOMING_TYPE}
311 * {@link android.provider.CallLog.Calls#OUTGOING_TYPE}, or
312 * {@link android.provider.CallLog.Calls#MISSED_TYPE}.
313 */
314 public String type;
315 public long date;
316 }
317
318 public QueryHandler(ContentResolver cr) {
319 super(cr);
320 }
321
322 /**
323 * Handles the query results.
324 */
325 @Override
326 protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
327 // TODO: it would be faster to use a join here, but for the purposes
328 // of this small record set, it should be ok.
329
330 // Note that CursorJoiner is not useable here because the number
331 // comparisons are not strictly equals; the comparisons happen in
332 // the SQL function PHONE_NUMBERS_EQUAL, which is not available for
333 // the CursorJoiner.
334
335 // Executing our own query is also feasible (with a join), but that
336 // will require some work (possibly destabilizing) in Contacts
337 // Provider.
338
339 // At this point, we will execute subqueries on each row just as
340 // CallLogActivity.java does.
341 switch (token) {
342 case CALL_LOG_TOKEN:
343 if (DBG) log("call log query complete.");
344
345 // initial call to retrieve the call list.
346 if (cursor != null) {
347 while (cursor.moveToNext()) {
348 // for each call in the call log list, create
349 // the notification object and query contacts
350 NotificationInfo n = getNotificationInfo (cursor);
351
352 if (DBG) log("query contacts for number: " + n.number);
353
354 mQueryHandler.startQuery(CONTACT_TOKEN, n,
355 Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, n.number),
356 PHONES_PROJECTION, null, null, PhoneLookup.NUMBER);
357 }
358
359 if (DBG) log("closing call log cursor.");
360 cursor.close();
361 }
362 break;
363 case CONTACT_TOKEN:
364 if (DBG) log("contact query complete.");
365
366 // subqueries to get the caller name.
367 if ((cursor != null) && (cookie != null)){
368 NotificationInfo n = (NotificationInfo) cookie;
369
370 Uri personUri = null;
371 if (cursor.moveToFirst()) {
372 n.name = cursor.getString(
373 cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
374 long person_id = cursor.getLong(
375 cursor.getColumnIndexOrThrow(PhoneLookup._ID));
376 if (DBG) {
377 log("contact :" + n.name + " found for phone: " + n.number
378 + ". id : " + person_id);
379 }
380 personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, person_id);
381 }
382
383 if (personUri != null) {
384 if (DBG) {
385 log("Start obtaining picture for the missed call. Uri: "
386 + personUri);
387 }
388 // Now try to obtain a photo for this person.
389 // ContactsAsyncHelper will do that and call onImageLoadComplete()
390 // after that.
391 ContactsAsyncHelper.startObtainPhotoAsync(
392 0, mContext, personUri, this, n);
393 } else {
394 if (DBG) {
395 log("Failed to find Uri for obtaining photo."
396 + " Just send notification without it.");
397 }
398 // We couldn't find person Uri, so we're sure we cannot obtain a photo.
399 // Call notifyMissedCall() right now.
400 notifyMissedCall(n.name, n.number, n.type, null, null, n.date);
401 }
402
403 if (DBG) log("closing contact cursor.");
404 cursor.close();
405 }
406 break;
407 default:
408 }
409 }
410
411 @Override
412 public void onImageLoadComplete(
413 int token, Drawable photo, Bitmap photoIcon, Object cookie) {
414 if (DBG) log("Finished loading image: " + photo);
415 NotificationInfo n = (NotificationInfo) cookie;
416 notifyMissedCall(n.name, n.number, n.type, photo, photoIcon, n.date);
417 }
418
419 /**
420 * Factory method to generate a NotificationInfo object given a
421 * cursor from the call log table.
422 */
423 private final NotificationInfo getNotificationInfo(Cursor cursor) {
424 NotificationInfo n = new NotificationInfo();
425 n.name = null;
426 n.number = cursor.getString(cursor.getColumnIndexOrThrow(Calls.NUMBER));
427 n.presentation = cursor.getInt(cursor.getColumnIndexOrThrow(Calls.NUMBER_PRESENTATION));
428 n.type = cursor.getString(cursor.getColumnIndexOrThrow(Calls.TYPE));
429 n.date = cursor.getLong(cursor.getColumnIndexOrThrow(Calls.DATE));
430
431 // make sure we update the number depending upon saved values in
432 // CallLog.addCall(). If either special values for unknown or
433 // private number are detected, we need to hand off the message
434 // to the missed call notification.
435 if (n.presentation != Calls.PRESENTATION_ALLOWED) {
436 n.number = null;
437 }
438
439 if (DBG) log("NotificationInfo constructed for number: " + n.number);
440
441 return n;
442 }
443 }
444
445 /**
446 * Configures a Notification to emit the blinky green message-waiting/
447 * missed-call signal.
448 */
449 private static void configureLedNotification(Notification note) {
450 note.flags |= Notification.FLAG_SHOW_LIGHTS;
451 note.defaults |= Notification.DEFAULT_LIGHTS;
452 }
453
454 /**
455 * Displays a notification about a missed call.
456 *
457 * @param name the contact name.
458 * @param number the phone number. Note that this may be a non-callable String like "Unknown",
459 * or "Private Number", which possibly come from methods like
460 * {@link PhoneUtils#modifyForSpecialCnapCases(Context, CallerInfo, String, int)}.
461 * @param type the type of the call. {@link android.provider.CallLog.Calls#INCOMING_TYPE}
462 * {@link android.provider.CallLog.Calls#OUTGOING_TYPE}, or
463 * {@link android.provider.CallLog.Calls#MISSED_TYPE}
464 * @param photo picture which may be used for the notification (when photoIcon is null).
465 * This also can be null when the picture itself isn't available. If photoIcon is available
466 * it should be prioritized (because this may be too huge for notification).
467 * See also {@link ContactsAsyncHelper}.
468 * @param photoIcon picture which should be used for the notification. Can be null. This is
469 * the most suitable for {@link android.app.Notification.Builder#setLargeIcon(Bitmap)}, this
470 * should be used when non-null.
471 * @param date the time when the missed call happened
472 */
473 /* package */ void notifyMissedCall(
474 String name, String number, String type, Drawable photo, Bitmap photoIcon, long date) {
475
476 // When the user clicks this notification, we go to the call log.
Yorke Leeca6ec3b2013-08-29 14:21:43 -0700477 final PendingIntent pendingCallLogIntent = PhoneGlobals.createPendingCallLogIntent(
478 mContext);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700479
480 // Never display the missed call notification on non-voice-capable
481 // devices, even if the device does somehow manage to get an
482 // incoming call.
483 if (!PhoneGlobals.sVoiceCapable) {
484 if (DBG) log("notifyMissedCall: non-voice-capable device, not posting notification");
485 return;
486 }
487
488 if (VDBG) {
489 log("notifyMissedCall(). name: " + name + ", number: " + number
490 + ", label: " + type + ", photo: " + photo + ", photoIcon: " + photoIcon
491 + ", date: " + date);
492 }
493
494 // title resource id
495 int titleResId;
496 // the text in the notification's line 1 and 2.
497 String expandedText, callName;
498
499 // increment number of missed calls.
500 mNumberMissedCalls++;
501
502 // get the name for the ticker text
503 // i.e. "Missed call from <caller name or number>"
504 if (name != null && TextUtils.isGraphic(name)) {
505 callName = name;
506 } else if (!TextUtils.isEmpty(number)){
Yorke Lee528bd1e2013-09-04 15:21:56 -0700507 final BidiFormatter bidiFormatter = BidiFormatter.getInstance();
508 // A number should always be displayed LTR using {@link BidiFormatter}
509 // regardless of the content of the rest of the notification.
510 callName = bidiFormatter.unicodeWrap(number, TextDirectionHeuristics.LTR);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700511 } else {
512 // use "unknown" if the caller is unidentifiable.
513 callName = mContext.getString(R.string.unknown);
514 }
515
516 // display the first line of the notification:
517 // 1 missed call: call name
518 // more than 1 missed call: <number of calls> + "missed calls"
519 if (mNumberMissedCalls == 1) {
520 titleResId = R.string.notification_missedCallTitle;
521 expandedText = callName;
522 } else {
523 titleResId = R.string.notification_missedCallsTitle;
524 expandedText = mContext.getString(R.string.notification_missedCallsMsg,
525 mNumberMissedCalls);
526 }
527
528 Notification.Builder builder = new Notification.Builder(mContext);
529 builder.setSmallIcon(android.R.drawable.stat_notify_missed_call)
530 .setTicker(mContext.getString(R.string.notification_missedCallTicker, callName))
531 .setWhen(date)
532 .setContentTitle(mContext.getText(titleResId))
533 .setContentText(expandedText)
Yorke Leeca6ec3b2013-08-29 14:21:43 -0700534 .setContentIntent(pendingCallLogIntent)
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700535 .setAutoCancel(true)
536 .setDeleteIntent(createClearMissedCallsIntent());
537
538 // Simple workaround for issue 6476275; refrain having actions when the given number seems
539 // not a real one but a non-number which was embedded by methods outside (like
540 // PhoneUtils#modifyForSpecialCnapCases()).
541 // TODO: consider removing equals() checks here, and modify callers of this method instead.
542 if (mNumberMissedCalls == 1
543 && !TextUtils.isEmpty(number)
544 && !TextUtils.equals(number, mContext.getString(R.string.private_num))
545 && !TextUtils.equals(number, mContext.getString(R.string.unknown))){
546 if (DBG) log("Add actions with the number " + number);
547
548 builder.addAction(R.drawable.stat_sys_phone_call,
549 mContext.getString(R.string.notification_missedCall_call_back),
550 PhoneGlobals.getCallBackPendingIntent(mContext, number));
551
552 builder.addAction(R.drawable.ic_text_holo_dark,
553 mContext.getString(R.string.notification_missedCall_message),
554 PhoneGlobals.getSendSmsFromNotificationPendingIntent(mContext, number));
555
556 if (photoIcon != null) {
557 builder.setLargeIcon(photoIcon);
558 } else if (photo instanceof BitmapDrawable) {
559 builder.setLargeIcon(((BitmapDrawable) photo).getBitmap());
560 }
561 } else {
562 if (DBG) {
563 log("Suppress actions. number: " + number + ", missedCalls: " + mNumberMissedCalls);
564 }
565 }
566
567 Notification notification = builder.getNotification();
568 configureLedNotification(notification);
569 mNotificationManager.notify(MISSED_CALL_NOTIFICATION, notification);
570 }
571
572 /** Returns an intent to be invoked when the missed call notification is cleared. */
573 private PendingIntent createClearMissedCallsIntent() {
574 Intent intent = new Intent(mContext, ClearMissedCallsService.class);
575 intent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS);
576 return PendingIntent.getService(mContext, 0, intent, 0);
577 }
578
579 /**
580 * Cancels the "missed call" notification.
581 *
582 * @see ITelephony.cancelMissedCallsNotification()
583 */
584 void cancelMissedCallNotification() {
585 // reset the number of missed calls to 0.
586 mNumberMissedCalls = 0;
587 mNotificationManager.cancel(MISSED_CALL_NOTIFICATION);
588 }
589
590 private void notifySpeakerphone() {
591 if (!mShowingSpeakerphoneIcon) {
592 mStatusBarManager.setIcon("speakerphone", android.R.drawable.stat_sys_speakerphone, 0,
593 mContext.getString(R.string.accessibility_speakerphone_enabled));
594 mShowingSpeakerphoneIcon = true;
595 }
596 }
597
598 private void cancelSpeakerphone() {
599 if (mShowingSpeakerphoneIcon) {
600 mStatusBarManager.removeIcon("speakerphone");
601 mShowingSpeakerphoneIcon = false;
602 }
603 }
604
605 /**
606 * Shows or hides the "speakerphone" notification in the status bar,
607 * based on the actual current state of the speaker.
608 *
609 * If you already know the current speaker state (e.g. if you just
610 * called AudioManager.setSpeakerphoneOn() yourself) then you should
611 * directly call {@link #updateSpeakerNotification(boolean)} instead.
612 *
613 * (But note that the status bar icon is *never* shown while the in-call UI
614 * is active; it only appears if you bail out to some other activity.)
615 */
616 private void updateSpeakerNotification() {
617 AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
618 boolean showNotification =
619 (mPhone.getState() == PhoneConstants.State.OFFHOOK) && audioManager.isSpeakerphoneOn();
620
621 if (DBG) log(showNotification
622 ? "updateSpeakerNotification: speaker ON"
623 : "updateSpeakerNotification: speaker OFF (or not offhook)");
624
625 updateSpeakerNotification(showNotification);
626 }
627
628 /**
629 * Shows or hides the "speakerphone" notification in the status bar.
630 *
631 * @param showNotification if true, call notifySpeakerphone();
632 * if false, call cancelSpeakerphone().
633 *
634 * Use {@link updateSpeakerNotification()} to update the status bar
635 * based on the actual current state of the speaker.
636 *
637 * (But note that the status bar icon is *never* shown while the in-call UI
638 * is active; it only appears if you bail out to some other activity.)
639 */
640 public void updateSpeakerNotification(boolean showNotification) {
641 if (DBG) log("updateSpeakerNotification(" + showNotification + ")...");
642
643 // Regardless of the value of the showNotification param, suppress
644 // the status bar icon if the the InCallScreen is the foreground
645 // activity, since the in-call UI already provides an onscreen
646 // indication of the speaker state. (This reduces clutter in the
647 // status bar.)
648 if (mApp.isShowingCallScreen()) {
649 cancelSpeakerphone();
650 return;
651 }
652
653 if (showNotification) {
654 notifySpeakerphone();
655 } else {
656 cancelSpeakerphone();
657 }
658 }
659
660 private void notifyMute() {
661 if (!mShowingMuteIcon) {
662 mStatusBarManager.setIcon("mute", android.R.drawable.stat_notify_call_mute, 0,
663 mContext.getString(R.string.accessibility_call_muted));
664 mShowingMuteIcon = true;
665 }
666 }
667
668 private void cancelMute() {
669 if (mShowingMuteIcon) {
670 mStatusBarManager.removeIcon("mute");
671 mShowingMuteIcon = false;
672 }
673 }
674
675 /**
676 * Shows or hides the "mute" notification in the status bar,
677 * based on the current mute state of the Phone.
678 *
679 * (But note that the status bar icon is *never* shown while the in-call UI
680 * is active; it only appears if you bail out to some other activity.)
681 */
682 void updateMuteNotification() {
683 // Suppress the status bar icon if the the InCallScreen is the
684 // foreground activity, since the in-call UI already provides an
685 // onscreen indication of the mute state. (This reduces clutter
686 // in the status bar.)
687 if (mApp.isShowingCallScreen()) {
688 cancelMute();
689 return;
690 }
691
692 if ((mCM.getState() == PhoneConstants.State.OFFHOOK) && PhoneUtils.getMute()) {
693 if (DBG) log("updateMuteNotification: MUTED");
694 notifyMute();
695 } else {
696 if (DBG) log("updateMuteNotification: not muted (or not offhook)");
697 cancelMute();
698 }
699 }
700
701 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700702 * Completely take down the in-call notification *and* the mute/speaker
703 * notifications as well, to indicate that the phone is now idle.
704 */
705 /* package */ void cancelCallInProgressNotifications() {
Chiao Cheng2ed66512013-09-15 18:17:23 -0700706 if (DBG) log("cancelCallInProgressNotifications");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700707 cancelMute();
708 cancelSpeakerphone();
709 }
710
711 /**
712 * Updates the message waiting indicator (voicemail) notification.
713 *
714 * @param visible true if there are messages waiting
715 */
716 /* package */ void updateMwi(boolean visible) {
717 if (DBG) log("updateMwi(): " + visible);
718
719 if (visible) {
720 int resId = android.R.drawable.stat_notify_voicemail;
721
722 // This Notification can get a lot fancier once we have more
723 // information about the current voicemail messages.
724 // (For example, the current voicemail system can't tell
725 // us the caller-id or timestamp of a message, or tell us the
726 // message count.)
727
728 // But for now, the UI is ultra-simple: if the MWI indication
729 // is supposed to be visible, just show a single generic
730 // notification.
731
732 String notificationTitle = mContext.getString(R.string.notification_voicemail_title);
733 String vmNumber = mPhone.getVoiceMailNumber();
734 if (DBG) log("- got vm number: '" + vmNumber + "'");
735
736 // Watch out: vmNumber may be null, for two possible reasons:
737 //
738 // (1) This phone really has no voicemail number
739 //
740 // (2) This phone *does* have a voicemail number, but
741 // the SIM isn't ready yet.
742 //
743 // Case (2) *does* happen in practice if you have voicemail
744 // messages when the device first boots: we get an MWI
745 // notification as soon as we register on the network, but the
746 // SIM hasn't finished loading yet.
747 //
748 // So handle case (2) by retrying the lookup after a short
749 // delay.
750
751 if ((vmNumber == null) && !mPhone.getIccRecordsLoaded()) {
752 if (DBG) log("- Null vm number: SIM records not loaded (yet)...");
753
754 // TODO: rather than retrying after an arbitrary delay, it
755 // would be cleaner to instead just wait for a
756 // SIM_RECORDS_LOADED notification.
757 // (Unfortunately right now there's no convenient way to
758 // get that notification in phone app code. We'd first
759 // want to add a call like registerForSimRecordsLoaded()
760 // to Phone.java and GSMPhone.java, and *then* we could
761 // listen for that in the CallNotifier class.)
762
763 // Limit the number of retries (in case the SIM is broken
764 // or missing and can *never* load successfully.)
765 if (mVmNumberRetriesRemaining-- > 0) {
766 if (DBG) log(" - Retrying in " + VM_NUMBER_RETRY_DELAY_MILLIS + " msec...");
767 mApp.notifier.sendMwiChangedDelayed(VM_NUMBER_RETRY_DELAY_MILLIS);
768 return;
769 } else {
770 Log.w(LOG_TAG, "NotificationMgr.updateMwi: getVoiceMailNumber() failed after "
771 + MAX_VM_NUMBER_RETRIES + " retries; giving up.");
772 // ...and continue with vmNumber==null, just as if the
773 // phone had no VM number set up in the first place.
774 }
775 }
776
777 if (TelephonyCapabilities.supportsVoiceMessageCount(mPhone)) {
778 int vmCount = mPhone.getVoiceMessageCount();
779 String titleFormat = mContext.getString(R.string.notification_voicemail_title_count);
780 notificationTitle = String.format(titleFormat, vmCount);
781 }
782
783 String notificationText;
784 if (TextUtils.isEmpty(vmNumber)) {
785 notificationText = mContext.getString(
786 R.string.notification_voicemail_no_vm_number);
787 } else {
788 notificationText = String.format(
789 mContext.getString(R.string.notification_voicemail_text_format),
790 PhoneNumberUtils.formatNumber(vmNumber));
791 }
792
793 Intent intent = new Intent(Intent.ACTION_CALL,
794 Uri.fromParts(Constants.SCHEME_VOICEMAIL, "", null));
795 PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
796
797 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
798 Uri ringtoneUri;
799 String uriString = prefs.getString(
800 CallFeaturesSetting.BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY, null);
801 if (!TextUtils.isEmpty(uriString)) {
802 ringtoneUri = Uri.parse(uriString);
803 } else {
804 ringtoneUri = Settings.System.DEFAULT_NOTIFICATION_URI;
805 }
806
807 Notification.Builder builder = new Notification.Builder(mContext);
808 builder.setSmallIcon(resId)
809 .setWhen(System.currentTimeMillis())
810 .setContentTitle(notificationTitle)
811 .setContentText(notificationText)
812 .setContentIntent(pendingIntent)
813 .setSound(ringtoneUri);
814 Notification notification = builder.getNotification();
815
816 CallFeaturesSetting.migrateVoicemailVibrationSettingsIfNeeded(prefs);
817 final boolean vibrate = prefs.getBoolean(
818 CallFeaturesSetting.BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, false);
819 if (vibrate) {
820 notification.defaults |= Notification.DEFAULT_VIBRATE;
821 }
822 notification.flags |= Notification.FLAG_NO_CLEAR;
823 configureLedNotification(notification);
824 mNotificationManager.notify(VOICEMAIL_NOTIFICATION, notification);
825 } else {
826 mNotificationManager.cancel(VOICEMAIL_NOTIFICATION);
827 }
828 }
829
830 /**
831 * Updates the message call forwarding indicator notification.
832 *
833 * @param visible true if there are messages waiting
834 */
835 /* package */ void updateCfi(boolean visible) {
836 if (DBG) log("updateCfi(): " + visible);
837 if (visible) {
838 // If Unconditional Call Forwarding (forward all calls) for VOICE
839 // is enabled, just show a notification. We'll default to expanded
840 // view for now, so the there is less confusion about the icon. If
841 // it is deemed too weird to have CF indications as expanded views,
842 // then we'll flip the flag back.
843
844 // TODO: We may want to take a look to see if the notification can
845 // display the target to forward calls to. This will require some
846 // effort though, since there are multiple layers of messages that
847 // will need to propagate that information.
848
849 Notification notification;
850 final boolean showExpandedNotification = true;
851 if (showExpandedNotification) {
852 Intent intent = new Intent(Intent.ACTION_MAIN);
853 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
854 intent.setClassName("com.android.phone",
855 "com.android.phone.CallFeaturesSetting");
856
857 notification = new Notification(
858 R.drawable.stat_sys_phone_call_forward, // icon
859 null, // tickerText
860 0); // The "timestamp" of this notification is meaningless;
861 // we only care about whether CFI is currently on or not.
862 notification.setLatestEventInfo(
863 mContext, // context
864 mContext.getString(R.string.labelCF), // expandedTitle
865 mContext.getString(R.string.sum_cfu_enabled_indicator), // expandedText
866 PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent
867 } else {
868 notification = new Notification(
869 R.drawable.stat_sys_phone_call_forward, // icon
870 null, // tickerText
871 System.currentTimeMillis() // when
872 );
873 }
874
875 notification.flags |= Notification.FLAG_ONGOING_EVENT; // also implies FLAG_NO_CLEAR
876
877 mNotificationManager.notify(
878 CALL_FORWARD_NOTIFICATION,
879 notification);
880 } else {
881 mNotificationManager.cancel(CALL_FORWARD_NOTIFICATION);
882 }
883 }
884
885 /**
886 * Shows the "data disconnected due to roaming" notification, which
887 * appears when you lose data connectivity because you're roaming and
888 * you have the "data roaming" feature turned off.
889 */
890 /* package */ void showDataDisconnectedRoaming() {
891 if (DBG) log("showDataDisconnectedRoaming()...");
892
893 // "Mobile network settings" screen / dialog
894 Intent intent = new Intent(mContext, com.android.phone.MobileNetworkSettings.class);
895
896 final CharSequence contentText = mContext.getText(R.string.roaming_reenable_message);
897
898 final Notification.Builder builder = new Notification.Builder(mContext);
899 builder.setSmallIcon(android.R.drawable.stat_sys_warning);
900 builder.setContentTitle(mContext.getText(R.string.roaming));
901 builder.setContentText(contentText);
902 builder.setContentIntent(PendingIntent.getActivity(mContext, 0, intent, 0));
903
904 final Notification notif = new Notification.BigTextStyle(builder).bigText(contentText)
905 .build();
906
907 mNotificationManager.notify(DATA_DISCONNECTED_ROAMING_NOTIFICATION, notif);
908 }
909
910 /**
911 * Turns off the "data disconnected due to roaming" notification.
912 */
913 /* package */ void hideDataDisconnectedRoaming() {
914 if (DBG) log("hideDataDisconnectedRoaming()...");
915 mNotificationManager.cancel(DATA_DISCONNECTED_ROAMING_NOTIFICATION);
916 }
917
918 /**
919 * Display the network selection "no service" notification
920 * @param operator is the numeric operator number
921 */
922 private void showNetworkSelection(String operator) {
923 if (DBG) log("showNetworkSelection(" + operator + ")...");
924
925 String titleText = mContext.getString(
926 R.string.notification_network_selection_title);
927 String expandedText = mContext.getString(
928 R.string.notification_network_selection_text, operator);
929
930 Notification notification = new Notification();
931 notification.icon = android.R.drawable.stat_sys_warning;
932 notification.when = 0;
933 notification.flags = Notification.FLAG_ONGOING_EVENT;
934 notification.tickerText = null;
935
936 // create the target network operators settings intent
937 Intent intent = new Intent(Intent.ACTION_MAIN);
938 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
939 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
940 // Use NetworkSetting to handle the selection intent
941 intent.setComponent(new ComponentName("com.android.phone",
942 "com.android.phone.NetworkSetting"));
943 PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
944
945 notification.setLatestEventInfo(mContext, titleText, expandedText, pi);
946
947 mNotificationManager.notify(SELECTED_OPERATOR_FAIL_NOTIFICATION, notification);
948 }
949
950 /**
951 * Turn off the network selection "no service" notification
952 */
953 private void cancelNetworkSelection() {
954 if (DBG) log("cancelNetworkSelection()...");
955 mNotificationManager.cancel(SELECTED_OPERATOR_FAIL_NOTIFICATION);
956 }
957
958 /**
959 * Update notification about no service of user selected operator
960 *
961 * @param serviceState Phone service state
962 */
963 void updateNetworkSelection(int serviceState) {
964 if (TelephonyCapabilities.supportsNetworkSelection(mPhone)) {
965 // get the shared preference of network_selection.
966 // empty is auto mode, otherwise it is the operator alpha name
967 // in case there is no operator name, check the operator numeric
968 SharedPreferences sp =
969 PreferenceManager.getDefaultSharedPreferences(mContext);
970 String networkSelection =
971 sp.getString(PhoneBase.NETWORK_SELECTION_NAME_KEY, "");
972 if (TextUtils.isEmpty(networkSelection)) {
973 networkSelection =
974 sp.getString(PhoneBase.NETWORK_SELECTION_KEY, "");
975 }
976
977 if (DBG) log("updateNetworkSelection()..." + "state = " +
978 serviceState + " new network " + networkSelection);
979
980 if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
981 && !TextUtils.isEmpty(networkSelection)) {
982 if (!mSelectedUnavailableNotify) {
983 showNetworkSelection(networkSelection);
984 mSelectedUnavailableNotify = true;
985 }
986 } else {
987 if (mSelectedUnavailableNotify) {
988 cancelNetworkSelection();
989 mSelectedUnavailableNotify = false;
990 }
991 }
992 }
993 }
994
995 /* package */ void postTransientNotification(int notifyId, CharSequence msg) {
996 if (mToast != null) {
997 mToast.cancel();
998 }
999
1000 mToast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
1001 mToast.show();
1002 }
1003
1004 private void log(String msg) {
1005 Log.d(LOG_TAG, msg);
1006 }
1007}