This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
/
PhoneApp.java
1670 lines (1497 loc) · 72.2 KB
/
PhoneApp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.app.Activity;
import android.app.Application;
import android.app.KeyguardManager;
import android.app.ProgressDialog;
import android.app.StatusBarManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncResult;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.IPowerManager;
import android.os.LocalPowerManager;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.preference.PreferenceManager;
import android.provider.Settings.System;
import android.telephony.ServiceState;
import android.util.Config;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CallManager;
import com.android.internal.telephony.IccCard;
import com.android.internal.telephony.MmiCode;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.cdma.EriInfo;
import com.android.internal.telephony.cdma.TtyIntent;
import com.android.internal.telephony.sip.SipPhoneFactory;
import com.android.phone.OtaUtils.CdmaOtaScreenState;
import com.android.server.sip.SipService;
/**
* Top-level Application class for the Phone app.
*/
public class PhoneApp extends Application implements AccelerometerListener.OrientationListener {
/* package */ static final String LOG_TAG = "PhoneApp";
/**
* Phone app-wide debug level:
* 0 - no debug logging
* 1 - normal debug logging if ro.debuggable is set (which is true in
* "eng" and "userdebug" builds but not "user" builds)
* 2 - ultra-verbose debug logging
*
* Most individual classes in the phone app have a local DBG constant,
* typically set to
* (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1)
* or else
* (PhoneApp.DBG_LEVEL >= 2)
* depending on the desired verbosity.
*
* ***** DO NOT SUBMIT WITH DBG_LEVEL > 0 *************
*/
/* package */ static final int DBG_LEVEL = 0;
private static final boolean DBG =
(PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2);
// Message codes; see mHandler below.
private static final int EVENT_SIM_NETWORK_LOCKED = 3;
private static final int EVENT_WIRED_HEADSET_PLUG = 7;
private static final int EVENT_SIM_STATE_CHANGED = 8;
private static final int EVENT_UPDATE_INCALL_NOTIFICATION = 9;
private static final int EVENT_DATA_ROAMING_DISCONNECTED = 10;
private static final int EVENT_DATA_ROAMING_OK = 11;
private static final int EVENT_UNSOL_CDMA_INFO_RECORD = 12;
private static final int EVENT_DOCK_STATE_CHANGED = 13;
private static final int EVENT_TTY_PREFERRED_MODE_CHANGED = 14;
private static final int EVENT_TTY_MODE_GET = 15;
private static final int EVENT_TTY_MODE_SET = 16;
private static final int EVENT_START_SIP_SERVICE = 17;
// The MMI codes are also used by the InCallScreen.
public static final int MMI_INITIATE = 51;
public static final int MMI_COMPLETE = 52;
public static final int MMI_CANCEL = 53;
// Don't use message codes larger than 99 here; those are reserved for
// the individual Activities of the Phone UI.
/**
* Allowable values for the poke lock code (timeout between a user activity and the
* going to sleep), please refer to {@link com.android.server.PowerManagerService}
* for additional reference.
* SHORT uses the short delay for the timeout (SHORT_KEYLIGHT_DELAY, 6 sec)
* MEDIUM uses the medium delay for the timeout (MEDIUM_KEYLIGHT_DELAY, 15 sec)
* DEFAULT is the system-wide default delay for the timeout (1 min)
*/
public enum ScreenTimeoutDuration {
SHORT,
MEDIUM,
DEFAULT
}
/**
* Allowable values for the wake lock code.
* SLEEP means the device can be put to sleep.
* PARTIAL means wake the processor, but we display can be kept off.
* FULL means wake both the processor and the display.
*/
public enum WakeState {
SLEEP,
PARTIAL,
FULL
}
private static PhoneApp sMe;
// A few important fields we expose to the rest of the package
// directly (rather than thru set/get methods) for efficiency.
Phone phone;
CallNotifier notifier;
Ringer ringer;
BluetoothHandsfree mBtHandsfree;
PhoneInterfaceManager phoneMgr;
CallManager mCM;
int mBluetoothHeadsetState = BluetoothHeadset.STATE_ERROR;
int mBluetoothHeadsetAudioState = BluetoothHeadset.STATE_ERROR;
boolean mShowBluetoothIndication = false;
static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
// Internal PhoneApp Call state tracker
CdmaPhoneCallState cdmaPhoneCallState;
// The InCallScreen instance (or null if the InCallScreen hasn't been
// created yet.)
private InCallScreen mInCallScreen;
// The currently-active PUK entry activity and progress dialog.
// Normally, these are the Emergency Dialer and the subsequent
// progress dialog. null if there is are no such objects in
// the foreground.
private Activity mPUKEntryActivity;
private ProgressDialog mPUKEntryProgressDialog;
private boolean mIsSimPinEnabled;
private String mCachedSimPin;
// True if a wired headset is currently plugged in, based on the state
// from the latest Intent.ACTION_HEADSET_PLUG broadcast we received in
// mReceiver.onReceive().
private boolean mIsHeadsetPlugged;
// True if the keyboard is currently *not* hidden
// Gets updated whenever there is a Configuration change
private boolean mIsHardKeyboardOpen;
// True if we are beginning a call, but the phone state has not changed yet
private boolean mBeginningCall;
// Last phone state seen by updatePhoneState()
Phone.State mLastPhoneState = Phone.State.IDLE;
private WakeState mWakeState = WakeState.SLEEP;
private ScreenTimeoutDuration mScreenTimeoutDuration = ScreenTimeoutDuration.DEFAULT;
private boolean mIgnoreTouchUserActivity = false;
private IBinder mPokeLockToken = new Binder();
private IPowerManager mPowerManagerService;
private PowerManager.WakeLock mWakeLock;
private PowerManager.WakeLock mPartialWakeLock;
private PowerManager.WakeLock mProximityWakeLock;
private KeyguardManager mKeyguardManager;
private StatusBarManager mStatusBarManager;
private int mStatusBarDisableCount;
private AccelerometerListener mAccelerometerListener;
private int mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN;
// Broadcast receiver for various intent broadcasts (see onCreate())
private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver();
// Broadcast receiver purely for ACTION_MEDIA_BUTTON broadcasts
private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
/** boolean indicating restoring mute state on InCallScreen.onResume() */
private boolean mShouldRestoreMuteOnInCallResume;
// Following are the CDMA OTA information Objects used during OTA Call.
// cdmaOtaProvisionData object store static OTA information that needs
// to be maintained even during Slider open/close scenarios.
// cdmaOtaConfigData object stores configuration info to control visiblity
// of each OTA Screens.
// cdmaOtaScreenState object store OTA Screen State information.
public OtaUtils.CdmaOtaProvisionData cdmaOtaProvisionData;
public OtaUtils.CdmaOtaConfigData cdmaOtaConfigData;
public OtaUtils.CdmaOtaScreenState cdmaOtaScreenState;
public OtaUtils.CdmaOtaInCallScreenUiState cdmaOtaInCallScreenUiState;
// TTY feature enabled on this platform
private boolean mTtyEnabled;
// Current TTY operating mode selected by user
private int mPreferredTtyMode = Phone.TTY_MODE_OFF;
/**
* Set the restore mute state flag. Used when we are setting the mute state
* OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)}
*/
/*package*/void setRestoreMuteOnInCallResume (boolean mode) {
mShouldRestoreMuteOnInCallResume = mode;
}
/**
* Get the restore mute state flag.
* This is used by the InCallScreen {@link InCallScreen#onResume()} to figure
* out if we need to restore the mute state for the current active call.
*/
/*package*/boolean getRestoreMuteOnInCallResume () {
return mShouldRestoreMuteOnInCallResume;
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Phone.State phoneState;
switch (msg.what) {
// Starts the SIP service. It's a no-op if SIP API is not supported
// on the deivce.
// TODO: Having the phone process host the SIP service is only
// temporary. Will move it to a persistent communication process
// later.
case EVENT_START_SIP_SERVICE:
SipService.start(getApplicationContext());
break;
// TODO: This event should be handled by the lock screen, just
// like the "SIM missing" and "Sim locked" cases (bug 1804111).
case EVENT_SIM_NETWORK_LOCKED:
if (getResources().getBoolean(R.bool.ignore_sim_network_locked_events)) {
// Some products don't have the concept of a "SIM network lock"
Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; "
+ "not showing 'SIM network unlock' PIN entry screen");
} else {
// Normal case: show the "SIM network unlock" PIN entry screen.
// The user won't be able to do anything else until
// they enter a valid SIM network PIN.
Log.i(LOG_TAG, "show sim depersonal panel");
IccNetworkDepersonalizationPanel ndpPanel =
new IccNetworkDepersonalizationPanel(PhoneApp.getInstance());
ndpPanel.show();
}
break;
case EVENT_UPDATE_INCALL_NOTIFICATION:
// Tell the NotificationMgr to update the "ongoing
// call" icon in the status bar, if necessary.
// Currently, this is triggered by a bluetooth headset
// state change (since the status bar icon needs to
// turn blue when bluetooth is active.)
if (DBG) Log.d (LOG_TAG, "- updating in-call notification from handler...");
NotificationMgr.getDefault().updateInCallNotification();
break;
case EVENT_DATA_ROAMING_DISCONNECTED:
NotificationMgr.getDefault().showDataDisconnectedRoaming();
break;
case EVENT_DATA_ROAMING_OK:
NotificationMgr.getDefault().hideDataDisconnectedRoaming();
break;
case MMI_COMPLETE:
onMMIComplete((AsyncResult) msg.obj);
break;
case MMI_CANCEL:
PhoneUtils.cancelMmiCode(phone);
break;
case EVENT_WIRED_HEADSET_PLUG:
// Since the presence of a wired headset or bluetooth affects the
// speakerphone, update the "speaker" state. We ONLY want to do
// this on the wired headset connect / disconnect events for now
// though, so we're only triggering on EVENT_WIRED_HEADSET_PLUG.
phoneState = mCM.getState();
// Do not change speaker state if phone is not off hook
if (phoneState == Phone.State.OFFHOOK) {
if (mBtHandsfree == null || !mBtHandsfree.isAudioOn()) {
if (!isHeadsetPlugged()) {
// if the state is "not connected", restore the speaker state.
PhoneUtils.restoreSpeakerMode(getApplicationContext());
} else {
// if the state is "connected", force the speaker off without
// storing the state.
PhoneUtils.turnOnSpeaker(getApplicationContext(), false, false);
}
}
}
// Update the Proximity sensor based on headset state
updateProximitySensorMode(phoneState);
// Force TTY state update according to new headset state
if (mTtyEnabled) {
sendMessage(obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
}
break;
case EVENT_SIM_STATE_CHANGED:
// Marks the event where the SIM goes into ready state.
// Right now, this is only used for the PUK-unlocking
// process.
if (msg.obj.equals(IccCard.INTENT_VALUE_ICC_READY)) {
// when the right event is triggered and there
// are UI objects in the foreground, we close
// them to display the lock panel.
if (mPUKEntryActivity != null) {
mPUKEntryActivity.finish();
mPUKEntryActivity = null;
}
if (mPUKEntryProgressDialog != null) {
mPUKEntryProgressDialog.dismiss();
mPUKEntryProgressDialog = null;
}
}
break;
case EVENT_UNSOL_CDMA_INFO_RECORD:
//TODO: handle message here;
break;
case EVENT_DOCK_STATE_CHANGED:
// If the phone is docked/undocked during a call, and no wired or BT headset
// is connected: turn on/off the speaker accordingly.
boolean inDockMode = false;
if (mDockState == Intent.EXTRA_DOCK_STATE_DESK ||
mDockState == Intent.EXTRA_DOCK_STATE_CAR) {
inDockMode = true;
}
if (VDBG) Log.d(LOG_TAG, "received EVENT_DOCK_STATE_CHANGED. Phone inDock = "
+ inDockMode);
phoneState = mCM.getState();
if (phoneState == Phone.State.OFFHOOK &&
!isHeadsetPlugged() &&
!(mBtHandsfree != null && mBtHandsfree.isAudioOn())) {
PhoneUtils.turnOnSpeaker(getApplicationContext(), inDockMode, true);
if (mInCallScreen != null) {
mInCallScreen.requestUpdateTouchUi();
}
}
case EVENT_TTY_PREFERRED_MODE_CHANGED:
// TTY mode is only applied if a headset is connected
int ttyMode;
if (isHeadsetPlugged()) {
ttyMode = mPreferredTtyMode;
} else {
ttyMode = Phone.TTY_MODE_OFF;
}
phone.setTTYMode(ttyMode, mHandler.obtainMessage(EVENT_TTY_MODE_SET));
break;
case EVENT_TTY_MODE_GET:
handleQueryTTYModeResponse(msg);
break;
case EVENT_TTY_MODE_SET:
handleSetTTYModeResponse(msg);
break;
}
}
};
public PhoneApp() {
sMe = this;
}
@Override
public void onCreate() {
if (VDBG) Log.v(LOG_TAG, "onCreate()...");
ContentResolver resolver = getContentResolver();
if (phone == null) {
// Initialize the telephony framework
PhoneFactory.makeDefaultPhones(this);
// Get the default phone
phone = PhoneFactory.getDefaultPhone();
mCM = CallManager.getInstance();
mCM.registerPhone(phone);
NotificationMgr.init(this);
phoneMgr = new PhoneInterfaceManager(this, phone);
mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE);
int phoneType = phone.getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
// Create an instance of CdmaPhoneCallState and initialize it to IDLE
cdmaPhoneCallState = new CdmaPhoneCallState();
cdmaPhoneCallState.CdmaPhoneCallStateInit();
}
if (BluetoothAdapter.getDefaultAdapter() != null) {
mBtHandsfree = new BluetoothHandsfree(this, mCM);
startService(new Intent(this, BluetoothHeadsetService.class));
} else {
// Device is not bluetooth capable
mBtHandsfree = null;
}
ringer = new Ringer(this);
// before registering for phone state changes
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP,
LOG_TAG);
// lock used to keep the processor awake, when we don't care for the display.
mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, LOG_TAG);
// Wake lock used to control proximity sensor behavior.
if ((pm.getSupportedWakeLockFlags()
& PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) {
mProximityWakeLock =
pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG);
}
if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock);
// create mAccelerometerListener only if we are using the proximity sensor
if (proximitySensorModeEnabled()) {
mAccelerometerListener = new AccelerometerListener(this, this);
}
mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
// get a handle to the service so that we can use it later when we
// want to set the poke lock.
mPowerManagerService = IPowerManager.Stub.asInterface(
ServiceManager.getService("power"));
notifier = new CallNotifier(this, phone, ringer, mBtHandsfree, new CallLogAsync());
// register for ICC status
IccCard sim = phone.getIccCard();
if (sim != null) {
if (VDBG) Log.v(LOG_TAG, "register for ICC status");
sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
}
// register for MMI/USSD
mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null);
// register connection tracking to PhoneUtils
PhoneUtils.initializeConnectionHandler(mCM);
// Read platform settings for TTY feature
mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled);
// Register for misc other intent broadcasts.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED);
intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
if (mTtyEnabled) {
intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION);
}
intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, intentFilter);
// Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts,
// since we need to manually adjust its priority (to make sure
// we get these intents *before* the media player.)
IntentFilter mediaButtonIntentFilter =
new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
//
// Make sure we're higher priority than the media player's
// MediaButtonIntentReceiver (which currently has the default
// priority of zero; see apps/Music/AndroidManifest.xml.)
mediaButtonIntentFilter.setPriority(1);
//
registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter);
//set the default values for the preferences in the phone.
PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
// Make sure the audio mode (along with some
// audio-mode-related state of our own) is initialized
// correctly, given the current state of the phone.
PhoneUtils.setAudioMode(mCM);
}
boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA);
if (phoneIsCdma) {
cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
}
// XXX pre-load the SimProvider so that it's ready
resolver.getType(Uri.parse("content://icc/adn"));
// start with the default value to set the mute state.
mShouldRestoreMuteOnInCallResume = false;
// TODO: Register for Cdma Information Records
// phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null);
// Read TTY settings and store it into BP NV.
// AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting
// to BP at power up (BP does not need to make the TTY setting persistent storage).
// This way, there is a single owner (i.e AP) for the TTY setting in the phone.
if (mTtyEnabled) {
mPreferredTtyMode = android.provider.Settings.Secure.getInt(
phone.getContext().getContentResolver(),
android.provider.Settings.Secure.PREFERRED_TTY_MODE,
Phone.TTY_MODE_OFF);
mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
}
// Read HAC settings and configure audio hardware
if (getResources().getBoolean(R.bool.hac_enabled)) {
int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(),
android.provider.Settings.System.HEARING_AID,
0);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ?
CallFeaturesSetting.HAC_VAL_ON :
CallFeaturesSetting.HAC_VAL_OFF);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
mIsHardKeyboardOpen = true;
} else {
mIsHardKeyboardOpen = false;
}
// Update the Proximity sensor based on keyboard state
updateProximitySensorMode(mCM.getState());
super.onConfigurationChanged(newConfig);
}
/**
* Returns the singleton instance of the PhoneApp.
*/
static PhoneApp getInstance() {
return sMe;
}
/**
* Returns the Phone associated with this instance
*/
static Phone getPhone() {
return getInstance().phone;
}
Ringer getRinger() {
return ringer;
}
BluetoothHandsfree getBluetoothHandsfree() {
return mBtHandsfree;
}
static Intent createCallLogIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW, null);
intent.setType("vnd.android.cursor.dir/calls");
return intent;
}
/**
* Return an Intent that can be used to bring up the in-call screen.
*
* This intent can only be used from within the Phone app, since the
* InCallScreen is not exported from our AndroidManifest.
*/
/* package */ static Intent createInCallIntent() {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
intent.setClassName("com.android.phone", getCallScreenClassName());
return intent;
}
/**
* Variation of createInCallIntent() that also specifies whether the
* DTMF dialpad should be initially visible when the InCallScreen
* comes up.
*/
/* package */ static Intent createInCallIntent(boolean showDialpad) {
Intent intent = createInCallIntent();
intent.putExtra(InCallScreen.SHOW_DIALPAD_EXTRA, showDialpad);
return intent;
}
static String getCallScreenClassName() {
return InCallScreen.class.getName();
}
/**
* Starts the InCallScreen Activity.
*/
private void displayCallScreen() {
if (VDBG) Log.d(LOG_TAG, "displayCallScreen()...");
startActivity(createInCallIntent());
Profiler.callScreenRequested();
}
boolean isSimPinEnabled() {
return mIsSimPinEnabled;
}
boolean authenticateAgainstCachedSimPin(String pin) {
return (mCachedSimPin != null && mCachedSimPin.equals(pin));
}
void setCachedSimPin(String pin) {
mCachedSimPin = pin;
}
void setInCallScreenInstance(InCallScreen inCallScreen) {
mInCallScreen = inCallScreen;
}
/**
* @return true if the in-call UI is running as the foreground
* activity. (In other words, from the perspective of the
* InCallScreen activity, return true between onResume() and
* onPause().)
*
* Note this method will return false if the screen is currently off,
* even if the InCallScreen *was* in the foreground just before the
* screen turned off. (This is because the foreground activity is
* always "paused" while the screen is off.)
*/
boolean isShowingCallScreen() {
if (mInCallScreen == null) return false;
return mInCallScreen.isForegroundActivity();
}
/**
* Dismisses the in-call UI.
*
* This also ensures that you won't be able to get back to the in-call
* UI via the BACK button (since this call removes the InCallScreen
* from the activity history.)
* For OTA Call, it call InCallScreen api to handle OTA Call End scenario
* to display OTA Call End screen.
*/
void dismissCallScreen() {
if (mInCallScreen != null) {
if ((phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) &&
(mInCallScreen.isOtaCallInActiveState()
|| mInCallScreen.isOtaCallInEndState()
|| ((cdmaOtaScreenState != null)
&& (cdmaOtaScreenState.otaScreenState
!= CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED)))) {
// TODO: During OTA Call, display should not become dark to
// allow user to see OTA UI update. Phone app needs to hold
// a SCREEN_DIM_WAKE_LOCK wake lock during the entire OTA call.
wakeUpScreen();
// If InCallScreen is not in foreground we resume it to show the OTA call end screen
// Fire off the InCallScreen intent
displayCallScreen();
mInCallScreen.handleOtaCallEnd();
return;
} else {
mInCallScreen.finish();
}
}
}
/**
* Handle OTA events
*
* When OTA call is active and display becomes dark, then CallNotifier will
* handle OTA Events by calling this api which then calls OtaUtil function.
*/
void handleOtaEvents(Message msg) {
if (DBG) Log.d(LOG_TAG, "Enter handleOtaEvents");
if ((mInCallScreen != null) && (!isShowingCallScreen())) {
if (mInCallScreen.otaUtils != null) {
mInCallScreen.otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj);
}
}
}
/**
* Sets the activity responsible for un-PUK-blocking the device
* so that we may close it when we receive a positive result.
* mPUKEntryActivity is also used to indicate to the device that
* we are trying to un-PUK-lock the phone. In other words, iff
* it is NOT null, then we are trying to unlock and waiting for
* the SIM to move to READY state.
*
* @param activity is the activity to close when PUK has
* finished unlocking. Can be set to null to indicate the unlock
* or SIM READYing process is over.
*/
void setPukEntryActivity(Activity activity) {
mPUKEntryActivity = activity;
}
Activity getPUKEntryActivity() {
return mPUKEntryActivity;
}
/**
* Sets the dialog responsible for notifying the user of un-PUK-
* blocking - SIM READYing progress, so that we may dismiss it
* when we receive a positive result.
*
* @param dialog indicates the progress dialog informing the user
* of the state of the device. Dismissed upon completion of
* READYing process
*/
void setPukEntryProgressDialog(ProgressDialog dialog) {
mPUKEntryProgressDialog = dialog;
}
ProgressDialog getPUKEntryProgressDialog() {
return mPUKEntryProgressDialog;
}
/**
* Disables the status bar. This is used by the phone app when in-call UI is active.
*
* Any call to this method MUST be followed (eventually)
* by a corresponding reenableStatusBar() call.
*/
/* package */ void disableStatusBar() {
if (DBG) Log.d(LOG_TAG, "disable status bar");
synchronized (this) {
if (mStatusBarDisableCount++ == 0) {
if (DBG) Log.d(LOG_TAG, "StatusBarManager.DISABLE_EXPAND");
mStatusBarManager.disable(StatusBarManager.DISABLE_EXPAND);
}
}
}
/**
* Re-enables the status bar after a previous disableStatusBar() call.
*
* Any call to this method MUST correspond to (i.e. be balanced with)
* a previous disableStatusBar() call.
*/
/* package */ void reenableStatusBar() {
if (DBG) Log.d(LOG_TAG, "re-enable status bar");
synchronized (this) {
if (mStatusBarDisableCount > 0) {
if (--mStatusBarDisableCount == 0) {
if (DBG) Log.d(LOG_TAG, "StatusBarManager.DISABLE_NONE");
mStatusBarManager.disable(StatusBarManager.DISABLE_NONE);
}
} else {
Log.e(LOG_TAG, "mStatusBarDisableCount is already zero");
}
}
}
/**
* Controls how quickly the screen times out.
*
* The poke lock controls how long it takes before the screen powers
* down, and therefore has no immediate effect when the current
* WakeState (see {@link PhoneApp#requestWakeState}) is FULL.
* If we're in a state where the screen *is* allowed to turn off,
* though, the poke lock will determine the timeout interval (long or
* short).
*
* @param shortPokeLock tells the device the timeout duration to use
* before going to sleep
* {@link com.android.server.PowerManagerService#SHORT_KEYLIGHT_DELAY}.
*/
/* package */ void setScreenTimeout(ScreenTimeoutDuration duration) {
if (VDBG) Log.d(LOG_TAG, "setScreenTimeout(" + duration + ")...");
// make sure we don't set the poke lock repeatedly so that we
// avoid triggering the userActivity calls in
// PowerManagerService.setPokeLock().
if (duration == mScreenTimeoutDuration) {
return;
}
// stick with default timeout if we are using the proximity sensor
if (proximitySensorModeEnabled()) {
return;
}
mScreenTimeoutDuration = duration;
updatePokeLock();
}
/**
* Update the state of the poke lock held by the phone app,
* based on the current desired screen timeout and the
* current "ignore user activity on touch" flag.
*/
private void updatePokeLock() {
// This is kind of convoluted, but the basic thing to remember is
// that the poke lock just sends a message to the screen to tell
// it to stay on for a while.
// The default is 0, for a long timeout and should be set that way
// when we are heading back into a the keyguard / screen off
// state, and also when we're trying to keep the screen alive
// while ringing. We'll also want to ignore the cheek events
// regardless of the timeout duration.
// The short timeout is really used whenever we want to give up
// the screen lock, such as when we're in call.
int pokeLockSetting = LocalPowerManager.POKE_LOCK_IGNORE_CHEEK_EVENTS;
switch (mScreenTimeoutDuration) {
case SHORT:
// Set the poke lock to timeout the display after a short
// timeout (5s). This ensures that the screen goes to sleep
// as soon as acceptably possible after we the wake lock
// has been released.
pokeLockSetting |= LocalPowerManager.POKE_LOCK_SHORT_TIMEOUT;
break;
case MEDIUM:
// Set the poke lock to timeout the display after a medium
// timeout (15s). This ensures that the screen goes to sleep
// as soon as acceptably possible after we the wake lock
// has been released.
pokeLockSetting |= LocalPowerManager.POKE_LOCK_MEDIUM_TIMEOUT;
break;
case DEFAULT:
default:
// set the poke lock to timeout the display after a long
// delay by default.
// TODO: it may be nice to be able to disable cheek presses
// for long poke locks (emergency dialer, for instance).
break;
}
if (mIgnoreTouchUserActivity) {
pokeLockSetting |= LocalPowerManager.POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS;
}
// Send the request
try {
mPowerManagerService.setPokeLock(pokeLockSetting, mPokeLockToken, LOG_TAG);
} catch (RemoteException e) {
Log.w(LOG_TAG, "mPowerManagerService.setPokeLock() failed: " + e);
}
}
/**
* Controls whether or not the screen is allowed to sleep.
*
* Once sleep is allowed (WakeState is SLEEP), it will rely on the
* settings for the poke lock to determine when to timeout and let
* the device sleep {@link PhoneApp#setScreenTimeout}.
*
* @param ws tells the device to how to wake.
*/
/* package */ void requestWakeState(WakeState ws) {
if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")...");
synchronized (this) {
if (mWakeState != ws) {
switch (ws) {
case PARTIAL:
// acquire the processor wake lock, and release the FULL
// lock if it is being held.
mPartialWakeLock.acquire();
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
break;
case FULL:
// acquire the full wake lock, and release the PARTIAL
// lock if it is being held.
mWakeLock.acquire();
if (mPartialWakeLock.isHeld()) {
mPartialWakeLock.release();
}
break;
case SLEEP:
default:
// release both the PARTIAL and FULL locks.
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
if (mPartialWakeLock.isHeld()) {
mPartialWakeLock.release();
}
break;
}
mWakeState = ws;
}
}
}
/**
* If we are not currently keeping the screen on, then poke the power
* manager to wake up the screen for the user activity timeout duration.
*/
/* package */ void wakeUpScreen() {
synchronized (this) {
if (mWakeState == WakeState.SLEEP) {
if (DBG) Log.d(LOG_TAG, "pulse screen lock");
try {
mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true);
} catch (RemoteException ex) {
// Ignore -- the system process is dead.
}
}
}
}
/**
* Sets the wake state and screen timeout based on the current state
* of the phone, and the current state of the in-call UI.
*
* This method is a "UI Policy" wrapper around
* {@link PhoneApp#requestWakeState} and {@link PhoneApp#setScreenTimeout}.
*
* It's safe to call this method regardless of the state of the Phone
* (e.g. whether or not it's idle), and regardless of the state of the
* Phone UI (e.g. whether or not the InCallScreen is active.)
*/
/* package */ void updateWakeState() {
Phone.State state = mCM.getState();
// True if the in-call UI is the foreground activity.
// (Note this will be false if the screen is currently off,
// since in that case *no* activity is in the foreground.)
boolean isShowingCallScreen = isShowingCallScreen();
// True if the InCallScreen's DTMF dialer is currently opened.
// (Note this does NOT imply whether or not the InCallScreen
// itself is visible.)
boolean isDialerOpened = (mInCallScreen != null) && mInCallScreen.isDialerOpened();
// True if the speakerphone is in use. (If so, we *always* use
// the default timeout. Since the user is obviously not holding
// the phone up to his/her face, we don't need to worry about
// false touches, and thus don't need to turn the screen off so
// aggressively.)
// Note that we need to make a fresh call to this method any
// time the speaker state changes. (That happens in
// PhoneUtils.turnOnSpeaker().)
boolean isSpeakerInUse = (state == Phone.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this);
// TODO (bug 1440854): The screen timeout *might* also need to
// depend on the bluetooth state, but this isn't as clear-cut as
// the speaker state (since while using BT it's common for the
// user to put the phone straight into a pocket, in which case the
// timeout should probably still be short.)
if (DBG) Log.d(LOG_TAG, "updateWakeState: callscreen " + isShowingCallScreen
+ ", dialer " + isDialerOpened