aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowTelecomManager.java
blob: 2a8459609c3ee82de8cf8a43d97994a5d1cf1945 (plain)
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
package org.robolectric.shadows;

import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.O;
import static android.os.Build.VERSION_CODES.R;
import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
import static com.google.common.base.Verify.verifyNotNull;

import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.telecom.CallAudioState;
import android.telecom.Connection;
import android.telecom.ConnectionRequest;
import android.telecom.ConnectionService;
import android.telecom.PhoneAccount;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telecom.VideoProfile;
import android.text.TextUtils;
import android.util.ArrayMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.robolectric.android.controller.ServiceController;
import org.robolectric.annotation.HiddenApi;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;

@Implements(value = TelecomManager.class, minSdk = LOLLIPOP)
public class ShadowTelecomManager {

  /**
   * Mode describing how the shadow handles incoming ({@link TelecomManager#addNewIncomingCall}) and
   * outgoing ({@link TelecomManager#placeCall}) call requests.
   */
  public enum CallRequestMode {
    /** Automatically allows all call requests. */
    ALLOW_ALL,

    /** Automatically denies all call requests. */
    DENY_ALL,

    /**
     * Do not automatically allow or deny any call requests. Instead, call requests should be
     * allowed or denied manually by calling the following methods:
     *
     * <ul>
     *   <li>{@link #allowIncomingCall(IncomingCallRecord)}
     *   <li>{@link #denyIncomingCall(IncomingCallRecord)}
     *   <li>{@link #allowOutgoingCall(OutgoingCallRecord)}
     *   <li>{@link #denyOutgoingCall(OutgoingCallRecord)}
     * </ul>
     */
    MANUAL,
  }

  @RealObject
  private TelecomManager realObject;

  private final LinkedHashMap<PhoneAccountHandle, PhoneAccount> accounts = new LinkedHashMap<>();
  private final LinkedHashMap<PhoneAccountHandle, String> voicemailNumbers = new LinkedHashMap<>();
  private final LinkedHashMap<PhoneAccountHandle, String> line1Numbers = new LinkedHashMap<>();

  private final List<IncomingCallRecord> incomingCalls = new ArrayList<>();
  private final List<OutgoingCallRecord> outgoingCalls = new ArrayList<>();
  private final List<UnknownCallRecord> unknownCalls = new ArrayList<>();
  private final Map<String, PhoneAccountHandle> defaultOutgoingPhoneAccounts = new ArrayMap<>();
  private Intent manageBlockNumbersIntent;
  private CallRequestMode callRequestMode = CallRequestMode.MANUAL;
  private PhoneAccountHandle simCallManager;
  private String defaultDialerPackageName;
  private String systemDefaultDialerPackageName;
  private boolean isInCall;
  private boolean ttySupported;
  private PhoneAccountHandle userSelectedOutgoingPhoneAccount;
  private boolean readPhoneStatePermission = true;
  private boolean callPhonePermission = true;
  private boolean handleMmiValue = false;
  private ConnectionService connectionService;

  public CallRequestMode getCallRequestMode() {
    return callRequestMode;
  }

  public void setCallRequestMode(CallRequestMode callRequestMode) {
    this.callRequestMode = callRequestMode;
  }

  /**
   * Set default outgoing phone account to be returned from {@link
   * #getDefaultOutgoingPhoneAccount(String)} for corresponding {@code uriScheme}.
   */
  public void setDefaultOutgoingPhoneAccount(String uriScheme, PhoneAccountHandle handle) {
    defaultOutgoingPhoneAccounts.put(uriScheme, handle);
  }

  /** Remove default outgoing phone account for corresponding {@code uriScheme}. */
  public void removeDefaultOutgoingPhoneAccount(String uriScheme) {
    defaultOutgoingPhoneAccounts.remove(uriScheme);
  }

  /**
   * Returns default outgoing phone account set through {@link
   * #setDefaultOutgoingPhoneAccount(String, PhoneAccountHandle)} for corresponding {@code
   * uriScheme}.
   */
  @Implementation
  protected PhoneAccountHandle getDefaultOutgoingPhoneAccount(String uriScheme) {
    return defaultOutgoingPhoneAccounts.get(uriScheme);
  }

  @Implementation
  @HiddenApi
  public PhoneAccountHandle getUserSelectedOutgoingPhoneAccount() {
    return userSelectedOutgoingPhoneAccount;
  }

  @Implementation
  @HiddenApi
  public void setUserSelectedOutgoingPhoneAccount(PhoneAccountHandle accountHandle) {
    userSelectedOutgoingPhoneAccount = accountHandle;
  }

  @Implementation
  protected PhoneAccountHandle getSimCallManager() {
    return simCallManager;
  }

  @Implementation(minSdk = M)
  @HiddenApi
  public PhoneAccountHandle getSimCallManager(int userId) {
    return null;
  }

  @Implementation
  @HiddenApi
  public PhoneAccountHandle getConnectionManager() {
    return this.getSimCallManager();
  }

  @Implementation
  @HiddenApi
  public List<PhoneAccountHandle> getPhoneAccountsSupportingScheme(String uriScheme) {
    List<PhoneAccountHandle> result = new ArrayList<>();

    for (PhoneAccountHandle handle : accounts.keySet()) {
      PhoneAccount phoneAccount = accounts.get(handle);
      if (phoneAccount.getSupportedUriSchemes().contains(uriScheme)) {
        result.add(handle);
      }
    }
    return result;
  }

  @Implementation(minSdk = M)
  protected List<PhoneAccountHandle> getCallCapablePhoneAccounts() {
    checkReadPhoneStatePermission();
    return this.getCallCapablePhoneAccounts(false);
  }

  @Implementation(minSdk = M)
  @HiddenApi
  public List<PhoneAccountHandle> getCallCapablePhoneAccounts(boolean includeDisabledAccounts) {
    List<PhoneAccountHandle> result = new ArrayList<>();

    for (PhoneAccountHandle handle : accounts.keySet()) {
      PhoneAccount phoneAccount = accounts.get(handle);
      if (!phoneAccount.isEnabled() && !includeDisabledAccounts) {
        continue;
      }
      result.add(handle);
    }
    return result;
  }

  @Implementation(minSdk = O)
  public List<PhoneAccountHandle> getSelfManagedPhoneAccounts() {
    List<PhoneAccountHandle> result = new ArrayList<>();

    for (PhoneAccountHandle handle : accounts.keySet()) {
      PhoneAccount phoneAccount = accounts.get(handle);
      if ((phoneAccount.getCapabilities() & PhoneAccount.CAPABILITY_SELF_MANAGED)
          == PhoneAccount.CAPABILITY_SELF_MANAGED) {
        result.add(handle);
      }
    }
    return result;
  }

  @Implementation
  @HiddenApi
  public List<PhoneAccountHandle> getPhoneAccountsForPackage() {
    Context context = ReflectionHelpers.getField(realObject, "mContext");

    List<PhoneAccountHandle> results = new ArrayList<>();
    for (PhoneAccountHandle handle : accounts.keySet()) {
      if (handle.getComponentName().getPackageName().equals(context.getPackageName())) {
        results.add(handle);
      }
    }
    return results;
  }

  @Implementation
  protected PhoneAccount getPhoneAccount(PhoneAccountHandle account) {
    checkReadPhoneStatePermission();
    return accounts.get(account);
  }

  @Implementation
  @HiddenApi
  public int getAllPhoneAccountsCount() {
    return accounts.size();
  }

  @Implementation
  @HiddenApi
  public List<PhoneAccount> getAllPhoneAccounts() {
    return ImmutableList.copyOf(accounts.values());
  }

  @Implementation
  @HiddenApi
  public List<PhoneAccountHandle> getAllPhoneAccountHandles() {
    return ImmutableList.copyOf(accounts.keySet());
  }

  @Implementation
  protected void registerPhoneAccount(PhoneAccount account) {
    account = adjustCapabilities(account);
    accounts.put(account.getAccountHandle(), account);
  }

  private PhoneAccount adjustCapabilities(PhoneAccount account) {
    // Mirror the capabilities adjustments done in com.android.server.telecom.PhoneAccountRegistrar.
    if (SDK_INT >= UPSIDE_DOWN_CAKE
        && account.hasCapabilities(PhoneAccount.CAPABILITY_SUPPORTS_TRANSACTIONAL_OPERATIONS)
        && !account.hasCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)) {
      return account.toBuilder()
          .setCapabilities(account.getCapabilities() | PhoneAccount.CAPABILITY_SELF_MANAGED)
          .build();
    }
    return account;
  }

  @Implementation
  protected void unregisterPhoneAccount(PhoneAccountHandle accountHandle) {
    accounts.remove(accountHandle);
  }

  /** @deprecated */
  @Deprecated
  @Implementation
  @HiddenApi
  public void clearAccounts() {
    accounts.clear();
  }

  @Implementation(minSdk = LOLLIPOP_MR1)
  @HiddenApi
  public void clearAccountsForPackage(String packageName) {
    Set<PhoneAccountHandle> phoneAccountHandlesInPackage = new HashSet<>();

    for (PhoneAccountHandle handle : accounts.keySet()) {
      if (handle.getComponentName().getPackageName().equals(packageName)) {
        phoneAccountHandlesInPackage.add(handle);
      }
    }

    for (PhoneAccountHandle handle : phoneAccountHandlesInPackage) {
      accounts.remove(handle);
    }
  }

  /** @deprecated */
  @Deprecated
  @Implementation
  @HiddenApi
  public ComponentName getDefaultPhoneApp() {
    return null;
  }

  @Implementation(minSdk = M)
  protected String getDefaultDialerPackage() {
    return defaultDialerPackageName;
  }

  /** @deprecated API deprecated since Q, for testing, use setDefaultDialerPackage instead */
  @Deprecated
  @Implementation(minSdk = M)
  @HiddenApi
  public boolean setDefaultDialer(String packageName) {
    this.defaultDialerPackageName = packageName;
    return true;
  }

  /** Set returned value of {@link #getDefaultDialerPackage()}. */
  public void setDefaultDialerPackage(String packageName) {
    this.defaultDialerPackageName = packageName;
  }

  @Implementation(minSdk = M)
  @HiddenApi // API goes public in Q
  protected String getSystemDialerPackage() {
    return systemDefaultDialerPackageName;
  }

  /** Set returned value of {@link #getSystemDialerPackage()}. */
  public void setSystemDialerPackage(String packageName) {
    this.systemDefaultDialerPackageName = packageName;
  }

  public void setVoicemailNumber(PhoneAccountHandle accountHandle, String number) {
    voicemailNumbers.put(accountHandle, number);
  }

  @Implementation(minSdk = M)
  protected boolean isVoiceMailNumber(PhoneAccountHandle accountHandle, String number) {
    return TextUtils.equals(number, voicemailNumbers.get(accountHandle));
  }

  @Implementation(minSdk = M)
  protected String getVoiceMailNumber(PhoneAccountHandle accountHandle) {
    return voicemailNumbers.get(accountHandle);
  }

  @Implementation(minSdk = LOLLIPOP_MR1)
  protected String getLine1Number(PhoneAccountHandle accountHandle) {
    checkReadPhoneStatePermission();
    return line1Numbers.get(accountHandle);
  }

  public void setLine1Number(PhoneAccountHandle accountHandle, String number) {
    line1Numbers.put(accountHandle, number);
  }

  /** Sets the return value for {@link TelecomManager#isInCall}. */
  public void setIsInCall(boolean isInCall) {
    this.isInCall = isInCall;
  }

  /**
   * Overrides behavior of {@link TelecomManager#isInCall} to return pre-set result.
   *
   * @return Value set by calling {@link ShadowTelecomManager#setIsInCall}. If setIsInCall has not
   *     previously been called, will return false.
   */
  @Implementation
  protected boolean isInCall() {
    return isInCall;
  }

  @Implementation
  @HiddenApi
  public int getCallState() {
    return 0;
  }

  @Implementation
  @HiddenApi
  public boolean isRinging() {
    for (IncomingCallRecord callRecord : incomingCalls) {
      if (callRecord.isRinging) {
        return true;
      }
    }
    for (UnknownCallRecord callRecord : unknownCalls) {
      if (callRecord.isRinging) {
        return true;
      }
    }
    return false;
  }

  @Implementation
  @HiddenApi
  public boolean endCall() {
    return false;
  }

  @Implementation
  protected void acceptRingingCall() {}

  @Implementation
  protected void silenceRinger() {
    for (IncomingCallRecord callRecord : incomingCalls) {
      callRecord.isRinging = false;
    }
    for (UnknownCallRecord callRecord : unknownCalls) {
      callRecord.isRinging = false;
    }
  }

  @Implementation
  protected boolean isTtySupported() {
    checkReadPhoneStatePermission();
    return ttySupported;
  }

  /** Sets the value to be returned by {@link #isTtySupported()}. */
  public void setTtySupported(boolean isSupported) {
    ttySupported = isSupported;
  }

  @Implementation
  @HiddenApi
  public int getCurrentTtyMode() {
    return 0;
  }

  @Implementation
  protected void addNewIncomingCall(PhoneAccountHandle phoneAccount, Bundle extras) {
    IncomingCallRecord call = new IncomingCallRecord(phoneAccount, extras);
    incomingCalls.add(call);

    switch (callRequestMode) {
      case ALLOW_ALL:
        allowIncomingCall(call);
        break;
      case DENY_ALL:
        denyIncomingCall(call);
        break;
      default:
        // Do nothing.
    }
  }

  public List<IncomingCallRecord> getAllIncomingCalls() {
    return ImmutableList.copyOf(incomingCalls);
  }

  public IncomingCallRecord getLastIncomingCall() {
    return Iterables.getLast(incomingCalls);
  }

  public IncomingCallRecord getOnlyIncomingCall() {
    return Iterables.getOnlyElement(incomingCalls);
  }

  /**
   * Allows an {@link IncomingCallRecord} created via {@link TelecomManager#addNewIncomingCall}.
   *
   * <p>Specifically, this method sets up the relevant {@link ConnectionService} and returns the
   * result of {@link ConnectionService#onCreateIncomingConnection}.
   */
  @TargetApi(M)
  @Nullable
  public Connection allowIncomingCall(IncomingCallRecord call) {
    if (call.isHandled) {
      throw new IllegalStateException("Call has already been allowed or denied.");
    }
    call.isHandled = true;

    PhoneAccountHandle phoneAccount = verifyNotNull(call.phoneAccount);
    ConnectionRequest request = buildConnectionRequestForIncomingCall(call);
    ConnectionService service = getConnectionService(phoneAccount);
    return service.onCreateIncomingConnection(phoneAccount, request);
  }

  /**
   * Denies an {@link IncomingCallRecord} created via {@link TelecomManager#addNewIncomingCall}.
   *
   * <p>Specifically, this method sets up the relevant {@link ConnectionService} and calls {@link
   * ConnectionService#onCreateIncomingConnectionFailed}.
   */
  @TargetApi(O)
  public void denyIncomingCall(IncomingCallRecord call) {
    if (call.isHandled) {
      throw new IllegalStateException("Call has already been allowed or denied.");
    }
    call.isHandled = true;

    PhoneAccountHandle phoneAccount = verifyNotNull(call.phoneAccount);
    ConnectionRequest request = buildConnectionRequestForIncomingCall(call);
    ConnectionService service = getConnectionService(phoneAccount);
    service.onCreateIncomingConnectionFailed(phoneAccount, request);
  }

  private static ConnectionRequest buildConnectionRequestForIncomingCall(IncomingCallRecord call) {
    PhoneAccountHandle phoneAccount = verifyNotNull(call.phoneAccount);
    Bundle extras = verifyNotNull(call.extras);
    Uri address = extras.getParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS);
    int videoState =
        extras.getInt(
            TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, VideoProfile.STATE_AUDIO_ONLY);
    return new ConnectionRequest(phoneAccount, address, new Bundle(extras), videoState);
  }

  @Implementation(minSdk = M)
  protected void placeCall(Uri address, Bundle extras) {
    checkCallPhonePermission();
    OutgoingCallRecord call = new OutgoingCallRecord(address, extras);
    outgoingCalls.add(call);

    switch (callRequestMode) {
      case ALLOW_ALL:
        allowOutgoingCall(call);
        break;
      case DENY_ALL:
        denyOutgoingCall(call);
        break;
      default:
        // Do nothing.
    }
  }

  public List<OutgoingCallRecord> getAllOutgoingCalls() {
    return ImmutableList.copyOf(outgoingCalls);
  }

  public OutgoingCallRecord getLastOutgoingCall() {
    return Iterables.getLast(outgoingCalls);
  }

  public OutgoingCallRecord getOnlyOutgoingCall() {
    return Iterables.getOnlyElement(outgoingCalls);
  }

  /**
   * Allows an {@link OutgoingCallRecord} created via {@link TelecomManager#placeCall}.
   *
   * <p>Specifically, this method sets up the relevant {@link ConnectionService} and returns the
   * result of {@link ConnectionService#onCreateOutgoingConnection}.
   */
  @TargetApi(M)
  @Nullable
  public Connection allowOutgoingCall(OutgoingCallRecord call) {
    if (call.isHandled) {
      throw new IllegalStateException("Call has already been allowed or denied.");
    }
    call.isHandled = true;

    PhoneAccountHandle phoneAccount = verifyNotNull(call.phoneAccount);
    ConnectionRequest request = buildConnectionRequestForOutgoingCall(call);
    ConnectionService service = getConnectionService(phoneAccount);
    return service.onCreateOutgoingConnection(phoneAccount, request);
  }

  /**
   * Denies an {@link OutgoingCallRecord} created via {@link TelecomManager#placeCall}.
   *
   * <p>Specifically, this method sets up the relevant {@link ConnectionService} and calls {@link
   * ConnectionService#onCreateOutgoingConnectionFailed}.
   */
  @TargetApi(O)
  public void denyOutgoingCall(OutgoingCallRecord call) {
    if (call.isHandled) {
      throw new IllegalStateException("Call has already been allowed or denied.");
    }
    call.isHandled = true;

    PhoneAccountHandle phoneAccount = verifyNotNull(call.phoneAccount);
    ConnectionRequest request = buildConnectionRequestForOutgoingCall(call);
    ConnectionService service = getConnectionService(phoneAccount);
    service.onCreateOutgoingConnectionFailed(phoneAccount, request);
  }

  private static ConnectionRequest buildConnectionRequestForOutgoingCall(OutgoingCallRecord call) {
    PhoneAccountHandle phoneAccount = verifyNotNull(call.phoneAccount);
    Uri address = verifyNotNull(call.address);
    Bundle extras = verifyNotNull(call.extras);
    Bundle outgoingCallExtras = extras.getBundle(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
    int videoState =
        extras.getInt(
            TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, VideoProfile.STATE_AUDIO_ONLY);
    return new ConnectionRequest(
        phoneAccount,
        address,
        outgoingCallExtras == null ? null : new Bundle(outgoingCallExtras),
        videoState);
  }

  @Implementation
  @HiddenApi
  public void addNewUnknownCall(PhoneAccountHandle phoneAccount, Bundle extras) {
    unknownCalls.add(new UnknownCallRecord(phoneAccount, extras));
  }

  public List<UnknownCallRecord> getAllUnknownCalls() {
    return ImmutableList.copyOf(unknownCalls);
  }

  public UnknownCallRecord getLastUnknownCall() {
    return Iterables.getLast(unknownCalls);
  }

  public UnknownCallRecord getOnlyUnknownCall() {
    return Iterables.getOnlyElement(unknownCalls);
  }

  /**
   * Set connection service.
   *
   * <p>This method can be used in case, when you already created connection service and would like
   * to use it in telecom manager instead of creating new one.
   *
   * @param service existing connection service
   */
  public void setConnectionService(ConnectionService service) {
    connectionService = service;
  }

  private ConnectionService getConnectionService(PhoneAccountHandle phoneAccount) {
    if (connectionService == null) {
      connectionService = setupConnectionService(phoneAccount);
    }
    return connectionService;
  }

  private static ConnectionService setupConnectionService(PhoneAccountHandle phoneAccount) {
    ComponentName service = phoneAccount.getComponentName();
    Class<? extends ConnectionService> clazz;
    try {
      clazz = Class.forName(service.getClassName()).asSubclass(ConnectionService.class);
    } catch (ClassNotFoundException e) {
      throw new IllegalArgumentException(e);
    }
    return verifyNotNull(
        ServiceController.of(ReflectionHelpers.callConstructor(clazz), null).create().get());
  }

  public void setHandleMmiValue(boolean handleMmiValue) {
    this.handleMmiValue = handleMmiValue;
  }

  @Implementation
  protected boolean handleMmi(String dialString) {
    return handleMmiValue;
  }

  @Implementation(minSdk = M)
  protected boolean handleMmi(String dialString, PhoneAccountHandle accountHandle) {
    return handleMmiValue;
  }

  @Implementation(minSdk = LOLLIPOP_MR1)
  protected Uri getAdnUriForPhoneAccount(PhoneAccountHandle accountHandle) {
    return Uri.parse("content://icc/adn");
  }

  @Implementation
  protected void cancelMissedCallsNotification() {}

  @Implementation
  protected void showInCallScreen(boolean showDialpad) {}

  @Implementation(minSdk = M)
  @HiddenApi
  public void enablePhoneAccount(PhoneAccountHandle handle, boolean isEnabled) {
    if (getPhoneAccount(handle) == null) {
      return;
    }
    getPhoneAccount(handle).setIsEnabled(isEnabled);
  }

  /**
   * Returns the intent set by {@link ShadowTelecomManager#setManageBlockNumbersIntent(Intent)} ()}
   */
  @Implementation(minSdk = N)
  protected Intent createManageBlockedNumbersIntent() {
    return this.manageBlockNumbersIntent;
  }

  /**
   * Sets the BlockNumbersIntent to be returned by {@link
   * ShadowTelecomManager#createManageBlockedNumbersIntent()}
   */
  public void setManageBlockNumbersIntent(Intent intent) {
    this.manageBlockNumbersIntent = intent;
  }

  @Implementation(maxSdk = LOLLIPOP_MR1)
  public void setSimCallManager(PhoneAccountHandle simCallManager) {
    this.simCallManager = simCallManager;
  }

  /**
   * Creates a new {@link CallAudioState}. The real constructor of {@link CallAudioState} is hidden.
   */
  public CallAudioState newCallAudioState(
      boolean muted,
      int route,
      int supportedRouteMask,
      BluetoothDevice activeBluetoothDevice,
      Collection<BluetoothDevice> supportedBluetoothDevices) {
    return new CallAudioState(
        muted, route, supportedRouteMask, activeBluetoothDevice, supportedBluetoothDevices);
  }

  @Implementation(minSdk = R)
  @SystemApi
  protected Intent createLaunchEmergencyDialerIntent(String number) {
    // copy of logic from TelecomManager service
    Context context = ReflectionHelpers.getField(realObject, "mContext");
    // use reflection to get resource id since it can vary based on SDK version, and compiler will
    // inline the value if used explicitly
    int configEmergencyDialerPackageId =
        ReflectionHelpers.getStaticField(
            com.android.internal.R.string.class, "config_emergency_dialer_package");
    String packageName = context.getString(configEmergencyDialerPackageId);
    Intent intent = new Intent(Intent.ACTION_DIAL_EMERGENCY).setPackage(packageName);
    ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, 0);
    if (resolveInfo == null) {
      // No matching activity from config, fallback to default platform implementation
      intent.setPackage(null);
    }
    if (!TextUtils.isEmpty(number) && TextUtils.isDigitsOnly(number)) {
      intent.setData(Uri.parse("tel:" + number));
    }
    return intent;
  }

  /**
   * Details about a call request made via {@link TelecomManager#addNewIncomingCall} or {@link
   * TelecomManager#addNewUnknownCall}.
   *
   * @deprecated Use {@link IncomingCallRecord} or {@link UnknownCallRecord} instead.
   */
  @Deprecated
  public static class CallRecord {
    public final PhoneAccountHandle phoneAccount;
    public final Bundle extras;
    protected boolean isRinging = true;

    /** @deprecated Use {@link extras} instead. */
    @Deprecated public final Bundle bundle;

    public CallRecord(PhoneAccountHandle phoneAccount, Bundle extras) {
      this.phoneAccount = phoneAccount;
      this.extras = extras == null ? null : new Bundle(extras);

      // Keep the deprecated "bundle" name around for a while.
      this.bundle = this.extras;
    }
  }

  /**
   * When set to false methods requiring {@link android.Manifest.permission.READ_PHONE_STATE}
   * permission will throw a {@link SecurityException}. By default it's set to true for backwards
   * compatibility.
   */
  public void setReadPhoneStatePermission(boolean readPhoneStatePermission) {
    this.readPhoneStatePermission = readPhoneStatePermission;
  }

  private void checkReadPhoneStatePermission() {
    if (!readPhoneStatePermission) {
      throw new SecurityException();
    }
  }

  /**
   * When set to false methods requiring {@link android.Manifest.permission.CALL_PHONE} permission
   * will throw a {@link SecurityException}. By default it's set to true for backwards
   * compatibility.
   */
  public void setCallPhonePermission(boolean callPhonePermission) {
    this.callPhonePermission = callPhonePermission;
  }

  private void checkCallPhonePermission() {
    if (!callPhonePermission) {
      throw new SecurityException();
    }
  }

  /** Details about an incoming call request made via {@link TelecomManager#addNewIncomingCall}. */
  public static class IncomingCallRecord extends CallRecord {
    private boolean isHandled = false;

    public IncomingCallRecord(PhoneAccountHandle phoneAccount, Bundle extras) {
      super(phoneAccount, extras);
    }
  }

  /** Details about an outgoing call request made via {@link TelecomManager#placeCall}. */
  public static class OutgoingCallRecord {
    public final PhoneAccountHandle phoneAccount;
    public final Uri address;
    public final Bundle extras;

    private boolean isHandled = false;

    public OutgoingCallRecord(Uri address, Bundle extras) {
      this.address = address;
      if (extras != null) {
        this.extras = new Bundle(extras);
        this.phoneAccount = extras.getParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
      } else {
        this.extras = null;
        this.phoneAccount = null;
      }
    }
  }

  /** Details about an unknown call request made via {@link TelecomManager#addNewUnknownCall}. */
  public static class UnknownCallRecord extends CallRecord {
    public UnknownCallRecord(PhoneAccountHandle phoneAccount, Bundle extras) {
      super(phoneAccount, extras);
    }
  }
}