1 /*
2  * Copyright (C) 2017 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 package android.telephony.euicc;
17 
18 import android.Manifest;
19 import android.annotation.FlaggedApi;
20 import android.annotation.IntDef;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.RequiresFeature;
24 import android.annotation.RequiresPermission;
25 import android.annotation.SdkConstant;
26 import android.annotation.SuppressAutoDoc;
27 import android.annotation.SystemApi;
28 import android.app.Activity;
29 import android.app.PendingIntent;
30 import android.compat.annotation.ChangeId;
31 import android.compat.annotation.EnabledSince;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentSender;
35 import android.content.pm.PackageManager;
36 import android.os.Build;
37 import android.os.Bundle;
38 import android.os.RemoteException;
39 import android.telephony.SubscriptionInfo;
40 import android.telephony.SubscriptionManager;
41 import android.telephony.TelephonyFrameworkInitializer;
42 import android.telephony.TelephonyManager;
43 import android.telephony.UiccCardInfo;
44 import android.telephony.euicc.EuiccCardManager.ResetOption;
45 import android.util.Log;
46 
47 import com.android.internal.telephony.euicc.IEuiccController;
48 import com.android.internal.telephony.flags.Flags;
49 
50 import java.lang.annotation.Retention;
51 import java.lang.annotation.RetentionPolicy;
52 import java.util.Collections;
53 import java.util.List;
54 import java.util.Locale;
55 import java.util.Set;
56 import java.util.stream.Collectors;
57 
58 /**
59  * EuiccManager is the application interface to eUICCs, or eSIMs/embedded SIMs.
60  *
61  * <p>You do not instantiate this class directly; instead, you retrieve an instance through
62  * {@link Context#getSystemService(String)} and {@link Context#EUICC_SERVICE}. This instance will be
63  * created using the default eUICC.
64  *
65  * <p>On a device with multiple eUICCs, you may want to create multiple EuiccManagers. To do this
66  * you can call {@link #createForCardId}.
67  *
68  * <p>See {@link #isEnabled} before attempting to use these APIs.
69  */
70 @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
71 public class EuiccManager {
72     private static final String TAG = "EuiccManager";
73 
74     /**
75      * Intent action to launch the embedded SIM (eUICC) management settings screen.
76      *
77      * <p>This screen shows a list of embedded profiles and offers the user the ability to switch
78      * between them, download new profiles, and delete unused profiles.
79      *
80      * <p>The activity will immediately finish with {@link android.app.Activity#RESULT_CANCELED} if
81      * {@link #isEnabled} is false.
82      *
83      * This is ued by non-LPA app to bring up LUI.
84      */
85     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
86     public static final String ACTION_MANAGE_EMBEDDED_SUBSCRIPTIONS =
87             "android.telephony.euicc.action.MANAGE_EMBEDDED_SUBSCRIPTIONS";
88 
89 
90     /**
91      * Intent action to transfer an embedded subscriptions.
92      *
93      * <p> Action sent by apps (such as the Settings app) to the Telephony framework to transfer an
94      * embedded subscription.
95      *
96      * <p> Requires that the calling app has the
97      * {@code android.Manifest.permission#MODIFY_PHONE_STATE} permission.
98      *
99      * <p>The activity will immediately finish with {@link android.app.Activity#RESULT_CANCELED} if
100      * {@link #isEnabled} is false.
101      *
102      * @hide
103      */
104     @SystemApi
105     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
106     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
107     public static final String ACTION_TRANSFER_EMBEDDED_SUBSCRIPTIONS =
108             "android.telephony.euicc.action.TRANSFER_EMBEDDED_SUBSCRIPTIONS";
109 
110     /**
111      * Intent action to convert the physical subscription to an embedded subscription.
112      *
113      * <p> Action sent by apps (such as the Settings app) to the Telephony framework to convert
114      * physical sim to embedded sim.
115      *
116      * <p> Requires that the calling app has the
117      * {@code android.Manifest.permission#MODIFY_PHONE_STATE} permission.
118      *
119      * <p>The activity will immediately finish with {@link android.app.Activity#RESULT_CANCELED} if
120      * {@link #isEnabled} is false.
121      *
122      * @hide
123      */
124     @SystemApi
125     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
126     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
127     public static final String ACTION_CONVERT_TO_EMBEDDED_SUBSCRIPTION =
128             "android.telephony.euicc.action.CONVERT_TO_EMBEDDED_SUBSCRIPTION";
129 
130     /**
131      * Broadcast Action: The eUICC OTA status is changed.
132      * <p class="note">
133      * Requires the {@link android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
134      *
135      * <p class="note">This is a protected intent that can only be sent
136      * by the system.
137      *
138      * @hide
139      */
140     @SystemApi
141     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
142     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
143     public static final String ACTION_OTA_STATUS_CHANGED =
144             "android.telephony.euicc.action.OTA_STATUS_CHANGED";
145 
146     /**
147      * Broadcast Action: The action sent to carrier app so it knows the carrier setup is not
148      * completed.
149      */
150     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
151     public static final String ACTION_NOTIFY_CARRIER_SETUP_INCOMPLETE =
152             "android.telephony.euicc.action.NOTIFY_CARRIER_SETUP_INCOMPLETE";
153 
154     /**
155      * Intent action to provision an embedded subscription.
156      *
157      * <p>May be called during device provisioning to launch a screen to perform embedded SIM
158      * provisioning, e.g. if no physical SIM is present and the user elects to configure their
159      * embedded SIM.
160      *
161      * <p>The activity will immediately finish with {@link android.app.Activity#RESULT_CANCELED} if
162      * {@link #isEnabled} is false.
163      *
164      * @hide
165      */
166     @SystemApi
167     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
168     public static final String ACTION_PROVISION_EMBEDDED_SUBSCRIPTION =
169             "android.telephony.euicc.action.PROVISION_EMBEDDED_SUBSCRIPTION";
170 
171     /**
172      * Intent action to handle a resolvable error.
173      * @hide
174      */
175     public static final String ACTION_RESOLVE_ERROR =
176             "android.telephony.euicc.action.RESOLVE_ERROR";
177 
178     /**
179      * Intent action sent by system apps (such as the Settings app) to the Telephony framework to
180      * enable or disable a subscription. Must be accompanied with {@link #EXTRA_SUBSCRIPTION_ID} and
181      * {@link #EXTRA_ENABLE_SUBSCRIPTION}, and optionally {@link #EXTRA_FROM_SUBSCRIPTION_ID}.
182      *
183      * <p>Requires the caller to be a privileged process with the
184      * {@link android.permission#CALL_PRIVILEGED} permission for the intent to reach the Telephony
185      * stack.
186      *
187      * <p>Unlike {@link #switchToSubscription(int, PendingIntent)}, using this action allows the
188      * underlying eUICC service (i.e. the LPA app) to control the UI experience during this
189      * operation. The action is received by the Telephony framework, which in turn selects and
190      * launches an appropriate LPA activity to present UI to the user. For example, the activity may
191      * show a confirmation dialog, a progress dialog, or an error dialog when necessary.
192      *
193      * <p>The launched activity will immediately finish with
194      * {@link android.app.Activity#RESULT_CANCELED} if {@link #isEnabled} is false.
195      *
196      * @hide
197      */
198     @SystemApi
199     public static final String ACTION_TOGGLE_SUBSCRIPTION_PRIVILEGED =
200             "android.telephony.euicc.action.TOGGLE_SUBSCRIPTION_PRIVILEGED";
201 
202     /**
203      * Intent action sent by system apps (such as the Settings app) to the Telephony framework to
204      * delete a subscription. Must be accompanied with {@link #EXTRA_SUBSCRIPTION_ID}.
205      *
206      * <p>Requires the caller to be a privileged process with the
207      * {@link android.permission#CALL_PRIVILEGED} permission for the intent to reach the Telephony
208      * stack.
209      *
210      * <p>Unlike {@link #deleteSubscription(int, PendingIntent)}, using this action allows the
211      * underlying eUICC service (i.e. the LPA app) to control the UI experience during this
212      * operation. The action is received by the Telephony framework, which in turn selects and
213      * launches an appropriate LPA activity to present UI to the user. For example, the activity may
214      * show a confirmation dialog, a progress dialog, or an error dialog when necessary.
215      *
216      * <p>The launched activity will immediately finish with
217      * {@link android.app.Activity#RESULT_CANCELED} if {@link #isEnabled} is false.
218      *
219      * @hide
220      */
221     @SystemApi
222     public static final String ACTION_DELETE_SUBSCRIPTION_PRIVILEGED =
223             "android.telephony.euicc.action.DELETE_SUBSCRIPTION_PRIVILEGED";
224 
225     /**
226      * Intent action sent by system apps (such as the Settings app) to the Telephony framework to
227      * rename a subscription. Must be accompanied with {@link #EXTRA_SUBSCRIPTION_ID} and
228      * {@link #EXTRA_SUBSCRIPTION_NICKNAME}.
229      *
230      * <p>Requires the caller to be a privileged process with the
231      * {@link android.permission#CALL_PRIVILEGED} permission for the intent to reach the Telephony
232      * stack.
233      *
234      * <p>Unlike {@link #updateSubscriptionNickname(int, String, PendingIntent)}, using this action
235      * allows the the underlying eUICC service (i.e. the LPA app) to control the UI experience
236      * during this operation. The action is received by the Telephony framework, which in turn
237      * selects and launches an appropriate LPA activity to present UI to the user. For example, the
238      * activity may show a confirmation dialog, a progress dialog, or an error dialog when
239      * necessary.
240      *
241      * <p>The launched activity will immediately finish with
242      * {@link android.app.Activity#RESULT_CANCELED} if {@link #isEnabled} is false.
243      *
244      * @hide
245      */
246     @SystemApi
247     public static final String ACTION_RENAME_SUBSCRIPTION_PRIVILEGED =
248             "android.telephony.euicc.action.RENAME_SUBSCRIPTION_PRIVILEGED";
249 
250     /**
251      * Intent action sent by a carrier app to launch the eSIM activation flow provided by the LPA UI
252      * (LUI). The carrier app must send this intent with one of the following:
253      *
254      * <p>{@link #EXTRA_USE_QR_SCANNER} not set or set to false: The LPA should try to get an
255      * activation code from the carrier app by binding to the carrier app service implementing
256      * {@code android.service.euicc.EuiccService#ACTION_BIND_CARRIER_PROVISIONING_SERVICE}.
257      * <p>{@link #EXTRA_USE_QR_SCANNER} set to true: The LPA should launch a QR scanner for the user
258      * to scan an eSIM profile QR code.
259      *
260      * <p>Upon completion, the LPA should return one of the following results to the carrier app:
261      *
262      * <p>{@code Activity.RESULT_OK}: The LPA has succeeded in downloading the new eSIM profile.
263      * <p>{@code Activity.RESULT_CANCELED}: The carrier app should treat this as if the user pressed
264      * the back button.
265      * <p>Anything else: The carrier app should treat this as an error.
266      *
267      * <p>LPA needs to check if caller's package name is allowed to perform this action.
268      **/
269     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
270     public static final String ACTION_START_EUICC_ACTIVATION =
271             "android.telephony.euicc.action.START_EUICC_ACTIVATION";
272 
273     /**
274      * Result code for an operation indicating that the operation succeeded.
275      */
276     public static final int EMBEDDED_SUBSCRIPTION_RESULT_OK = 0;
277 
278     /**
279      * Result code for an operation indicating that the user must take some action before the
280      * operation can continue.
281      *
282      * @see #startResolutionActivity
283      */
284     public static final int EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR = 1;
285 
286     /**
287      * Result code for an operation indicating that an unresolvable error occurred.
288      *
289      * {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE} will be populated with a detailed error
290      * code for logging/debugging purposes only.
291      */
292     public static final int EMBEDDED_SUBSCRIPTION_RESULT_ERROR = 2;
293 
294     /**
295      * Key for an extra set on the {@link #ACTION_PROVISION_EMBEDDED_SUBSCRIPTION} intent for which
296      * kind of activation flow will be evolved. (see {@code EUICC_ACTIVATION_})
297      *
298      * @hide
299      */
300     @SystemApi
301     public static final String EXTRA_ACTIVATION_TYPE =
302             "android.telephony.euicc.extra.ACTIVATION_TYPE";
303 
304     /**
305      * Key for an extra set on {@link PendingIntent} result callbacks providing a detailed result
306      * code.
307      *
308      * <p>The value of this key is an integer and contains two portions. The first byte is
309      * OperationCode and the reaming three bytes is the ErrorCode.
310      *
311      * OperationCode is the first byte of the result code and is a categorization which defines what
312      * type of operation took place when an error occurred. e.g {@link #OPERATION_DOWNLOAD} means
313      * the error is related to download.Since the OperationCode only uses at most one byte, the
314      * maximum allowed quantity is 255(0xFF).
315      *
316      * ErrorCode is the remaining three bytes of the result code, and it denotes what happened.
317      * e.g a combination of {@link #OPERATION_DOWNLOAD} and {@link #ERROR_TIME_OUT} will suggest the
318      * download operation has timed out. The only exception here is
319      * {@link #OPERATION_SMDX_SUBJECT_REASON_CODE}, where instead of ErrorCode, SubjectCode[5.2.6.1
320      * from GSMA (SGP.22 v2.2) and ReasonCode[5.2.6.2] from GSMA (SGP.22 v2.2) are encoded. @see
321      * {@link #EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE} and
322      * {@link #EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE}
323      *
324      * In the case where ErrorCode contains a value of 0, it means it's an unknown error. E.g Intent
325      * only contains {@link #OPERATION_DOWNLOAD} and ErrorCode is 0 implies this is an unknown
326      * Download error.
327      *
328      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_OPERATION_CODE
329      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_ERROR_CODE
330      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE
331      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE
332      */
333     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE =
334             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_DETAILED_CODE";
335 
336     /**
337      * Key for an extra set on {@link PendingIntent} result callbacks providing a
338      * OperationCode of {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE},
339      * value will be an int.
340      */
341     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_OPERATION_CODE =
342             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_OPERATION_CODE";
343 
344     /**
345      * Key for an extra set on {@link PendingIntent} result callbacks providing a
346      * ErrorCode of {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE},
347      * value will be an int.
348      */
349     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_ERROR_CODE =
350             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_ERROR_CODE";
351 
352     /**
353      * Key for an extra set on {@link PendingIntent} result callbacks providing a
354      * SubjectCode[5.2.6.1] from GSMA (SGP.22 v2.2) decoded from
355      * {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE}.
356      * The value of this extra will be a String.
357      */
358     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE =
359             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE";
360 
361     /**
362      * Key for an extra set on {@link PendingIntent} result callbacks providing a
363      * ReasonCode[5.2.6.2] from GSMA (SGP.22 v2.2) decoded from
364      * {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE}.
365      * The value of this extra will be a String.
366      */
367     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE =
368             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE";
369 
370     /**
371      * Key for an extra set on {@code #getDownloadableSubscriptionMetadata} PendingIntent result
372      * callbacks providing the downloadable subscription metadata.
373      */
374     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTION =
375             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTION";
376 
377     /**
378      * Key for an extra set on {@link #getDefaultDownloadableSubscriptionList} PendingIntent result
379      * callbacks providing the list of available downloadable subscriptions.
380      * @hide
381      */
382     @SystemApi
383     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTIONS =
384             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTIONS";
385 
386     /**
387      * Key for an extra set on {@link PendingIntent} result callbacks providing the resolution
388      * pending intent for {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR}s.
389      * @hide
390      */
391     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_INTENT =
392             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_RESOLUTION_INTENT";
393 
394     /**
395      * Key for an extra set on the {@link #EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_INTENT} intent
396      * containing the EuiccService action to launch for resolution.
397      * @hide
398      */
399     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_ACTION =
400             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_RESOLUTION_ACTION";
401 
402     /**
403      * Key for an extra set on the {@link #EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_INTENT} intent
404      * providing the callback to execute after resolution is completed.
405      * @hide
406      */
407     public static final String EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_CALLBACK_INTENT =
408             "android.telephony.euicc.extra.EMBEDDED_SUBSCRIPTION_RESOLUTION_CALLBACK_INTENT";
409 
410     /**
411      * Key for an extra set on the {@link #ACTION_PROVISION_EMBEDDED_SUBSCRIPTION} intent for
412      * whether eSIM provisioning flow is forced to be started or not. If this extra hasn't been
413      * set, eSIM provisioning flow may be skipped and the corresponding carrier's app will be
414      * notified. Otherwise, eSIM provisioning flow will be started when
415      * {@link #ACTION_PROVISION_EMBEDDED_SUBSCRIPTION} has been received.
416      * @hide
417      */
418     @SystemApi
419     public static final String EXTRA_FORCE_PROVISION =
420             "android.telephony.euicc.extra.FORCE_PROVISION";
421 
422     /**
423      * Key for an extra set on privileged actions {@link #ACTION_TOGGLE_SUBSCRIPTION_PRIVILEGED},
424      * {@link #ACTION_DELETE_SUBSCRIPTION_PRIVILEGED}, and
425      * {@link #ACTION_RENAME_SUBSCRIPTION_PRIVILEGED} providing the ID of the targeted subscription.
426      *
427      * <p>Expected type of the extra data: int
428      *
429      * @hide
430      */
431     @SystemApi
432     public static final String EXTRA_SUBSCRIPTION_ID =
433             "android.telephony.euicc.extra.SUBSCRIPTION_ID";
434 
435     /**
436      * Key for an extra set on {@link #ACTION_TOGGLE_SUBSCRIPTION_PRIVILEGED} providing a boolean
437      * value of whether to enable or disable the targeted subscription.
438      *
439      * <p>Expected type of the extra data: boolean
440      *
441      * @hide
442      */
443     @SystemApi
444     public static final String EXTRA_ENABLE_SUBSCRIPTION =
445             "android.telephony.euicc.extra.ENABLE_SUBSCRIPTION";
446 
447     /**
448      * Key for an extra set on {@link #ACTION_RENAME_SUBSCRIPTION_PRIVILEGED} providing a new
449      * nickname for the targeted subscription.
450      *
451      * <p>Expected type of the extra data: String
452      *
453      * @hide
454      */
455     @SystemApi
456     public static final String EXTRA_SUBSCRIPTION_NICKNAME =
457             "android.telephony.euicc.extra.SUBSCRIPTION_NICKNAME";
458 
459     /**
460      * Key for an extra set on {@link #ACTION_TOGGLE_SUBSCRIPTION_PRIVILEGED} providing the ID of
461      * the subscription we're toggling from. This extra is optional and is only used for UI
462      * purposes by the underlying eUICC service (i.e. the LPA app), such as displaying a dialog
463      * titled "Switch X with Y". If set, the provided subscription will be used as the "from"
464      * subscription in UI (the "X" in the dialog example). Otherwise, the currently active
465      * subscription that will be disabled is the "from" subscription.
466      *
467      * <p>Expected type of the extra data: int
468      *
469      * @hide
470      */
471     @SystemApi
472     public static final String EXTRA_FROM_SUBSCRIPTION_ID =
473             "android.telephony.euicc.extra.FROM_SUBSCRIPTION_ID";
474 
475     /**
476      * Key for an extra set on privileged actions {@link #ACTION_TOGGLE_SUBSCRIPTION_PRIVILEGED}
477      * providing the physical slot ID of the target slot.
478      *
479      * <p>Expected type of the extra data: int
480      *
481      * @hide
482      */
483     @SystemApi
484     public static final String EXTRA_PHYSICAL_SLOT_ID =
485             "android.telephony.euicc.extra.PHYSICAL_SLOT_ID";
486 
487 
488     /**
489      * Key for an extra set on actions {@link #ACTION_START_EUICC_ACTIVATION} providing a boolean
490      * value of whether to start eSIM activation with QR scanner.
491      *
492      * <p>Expected type of the extra data: boolean
493      **/
494     public static final String EXTRA_USE_QR_SCANNER =
495             "android.telephony.euicc.extra.USE_QR_SCANNER";
496 
497     /**
498      * Optional meta-data attribute for a carrier app providing an icon to use to represent the
499      * carrier. If not provided, the app's launcher icon will be used as a fallback.
500      */
501     public static final String META_DATA_CARRIER_ICON = "android.telephony.euicc.carriericon";
502 
503     /**
504      * Euicc activation type which will be included in {@link #EXTRA_ACTIVATION_TYPE} and used to
505      * decide which kind of activation flow should be lauched.
506      *
507      * @hide
508      */
509     @Retention(RetentionPolicy.SOURCE)
510     @IntDef(prefix = {"EUICC_ACTIVATION_"}, value = {
511             EUICC_ACTIVATION_TYPE_DEFAULT,
512             EUICC_ACTIVATION_TYPE_BACKUP,
513             EUICC_ACTIVATION_TYPE_TRANSFER,
514             EUICC_ACTIVATION_TYPE_ACCOUNT_REQUIRED,
515             EUICC_ACTIVATION_TYPE_TRANSFER_FINAL_HOLD,
516     })
517     public @interface EuiccActivationType{}
518 
519 
520     /**
521      * The default euicc activation type which includes checking server side and downloading the
522      * profile based on carrier's download configuration.
523      *
524      * @hide
525      */
526     @SystemApi
527     public static final int EUICC_ACTIVATION_TYPE_DEFAULT = 1;
528 
529     /**
530      * The euicc activation type used when the default download process failed. LPA will start the
531      * backup flow and try to download the profile for the carrier.
532      *
533      * @hide
534      */
535     @SystemApi
536     public static final int EUICC_ACTIVATION_TYPE_BACKUP = 2;
537 
538     /**
539      * The activation flow of eSIM seamless transfer will be used. LPA will start normal eSIM
540      * activation flow and if it's failed, the name of the carrier selected will be recorded. After
541      * the future device pairing, LPA will contact this carrier to transfer it from the other device
542      * to this device.
543      *
544      * @hide
545      */
546     @SystemApi
547     public static final int EUICC_ACTIVATION_TYPE_TRANSFER = 3;
548 
549     /**
550      * The activation flow of eSIM requiring user account will be started. This can only be used
551      * when there is user account signed in. Otherwise, the flow will be failed.
552      *
553      * @hide
554      */
555     @SystemApi
556     public static final int EUICC_ACTIVATION_TYPE_ACCOUNT_REQUIRED = 4;
557 
558     /**
559      * The activation flow of eSIM transfer to block the transfer process before B&R flow.
560      * This is needed to avoid connection overlapping between eSIM connection B&R connection.
561      *
562      * @hide
563      */
564      // TODO(b/329212614): add system api annotation during the allowed api timeline.
565      public static final int EUICC_ACTIVATION_TYPE_TRANSFER_FINAL_HOLD = 5;
566 
567     /**
568      * Euicc OTA update status which can be got by {@link #getOtaStatus}
569      * @removed mistakenly exposed as system-api previously
570      */
571     @Retention(RetentionPolicy.SOURCE)
572     @IntDef(prefix = {"EUICC_OTA_"}, value = {
573             EUICC_OTA_IN_PROGRESS,
574             EUICC_OTA_FAILED,
575             EUICC_OTA_SUCCEEDED,
576             EUICC_OTA_NOT_NEEDED,
577             EUICC_OTA_STATUS_UNAVAILABLE
578 
579     })
580     public @interface OtaStatus{}
581 
582     /**
583      * An OTA is in progress. During this time, the eUICC is not available and the user may lose
584      * network access.
585      * @hide
586      */
587     @SystemApi
588     public static final int EUICC_OTA_IN_PROGRESS = 1;
589 
590     /**
591      * The OTA update failed.
592      * @hide
593      */
594     @SystemApi
595     public static final int EUICC_OTA_FAILED = 2;
596 
597     /**
598      * The OTA update finished successfully.
599      * @hide
600      */
601     @SystemApi
602     public static final int EUICC_OTA_SUCCEEDED = 3;
603 
604     /**
605      * The OTA update not needed since current eUICC OS is latest.
606      * @hide
607      */
608     @SystemApi
609     public static final int EUICC_OTA_NOT_NEEDED = 4;
610 
611     /**
612      * The OTA status is unavailable since eUICC service is unavailable.
613      * @hide
614      */
615     @SystemApi
616     public static final int EUICC_OTA_STATUS_UNAVAILABLE = 5;
617 
618     /**
619      * List of OperationCode corresponding to {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE}'s
620      * value, an integer. @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
621      *
622      * @hide
623      */
624     @Retention(RetentionPolicy.SOURCE)
625     @IntDef(prefix = {"OPERATION_"}, value = {
626             OPERATION_SYSTEM,
627             OPERATION_SIM_SLOT,
628             OPERATION_EUICC_CARD,
629             OPERATION_SWITCH,
630             OPERATION_DOWNLOAD,
631             OPERATION_METADATA,
632             OPERATION_EUICC_GSMA,
633             OPERATION_APDU,
634             OPERATION_SMDX,
635             OPERATION_HTTP,
636             OPERATION_SMDX_SUBJECT_REASON_CODE,
637     })
638     public @interface OperationCode {
639     }
640 
641     /**
642      * Internal system error.
643      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
644      */
645     public static final int OPERATION_SYSTEM = 1;
646 
647     /**
648      * SIM slot error. Failed to switch slot, failed to access the physical slot etc.
649      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
650      */
651     public static final int OPERATION_SIM_SLOT = 2;
652 
653     /**
654      * eUICC card error.
655      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
656      */
657     public static final int OPERATION_EUICC_CARD = 3;
658 
659     /**
660      * Generic switching profile error
661      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
662      */
663     public static final int OPERATION_SWITCH = 4;
664 
665     /**
666      * Download profile error.
667      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
668      */
669     public static final int OPERATION_DOWNLOAD = 5;
670 
671     /**
672      * Subscription's metadata error
673      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
674      */
675     public static final int OPERATION_METADATA = 6;
676 
677     /**
678      * eUICC returned an error defined in GSMA (SGP.22 v2.2) while running one of the ES10x
679      * functions.
680      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
681      */
682     public static final int OPERATION_EUICC_GSMA = 7;
683 
684     /**
685      * The exception of failing to execute an APDU command. It can be caused by an error
686      * happening on opening the basic or logical channel, or the response of the APDU command is
687      * not success (0x9000).
688      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
689      */
690     public static final int OPERATION_APDU = 8;
691 
692     /**
693      * SMDX(SMDP/SMDS) error
694      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
695      */
696     public static final int OPERATION_SMDX = 9;
697 
698     /**
699      * SubjectCode[5.2.6.1] and ReasonCode[5.2.6.2] error from GSMA (SGP.22 v2.2)
700      * When {@link #OPERATION_SMDX_SUBJECT_REASON_CODE} is used as the
701      * {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE}, the remaining three bytes of the integer
702      * result from {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE} will be used to stored the
703      * SubjectCode and ReasonCode from the GSMA spec and NOT ErrorCode.
704      *
705      * The encoding will follow the format of:
706      * 1. The first byte of the result will be 255(0xFF).
707      * 2. Remaining three bytes(24 bits) will be split into six sections, 4 bits in each section.
708      * 3. A SubjectCode/ReasonCode will take 12 bits each.
709      * 4. The maximum number can be represented per section is 15, as that is the maximum number
710      * allowed to be stored into 4 bits
711      * 5. Maximum supported nested category from GSMA is three layers. E.g 8.11.1.2 is not
712      * supported.
713      *
714      * E.g given SubjectCode(8.11.1) and ReasonCode(5.1)
715      *
716      * Base10:  0       10      8       11      1       0       5       1
717      * Base2:   0000    1010    1000    1011    0001    0000    0101    0001
718      * Base16:  0       A       8       B       1       0       5       1
719      *
720      * Thus the integer stored in {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE} is
721      * 0xA8B1051(176885841)
722      *
723      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
724      */
725     public static final int OPERATION_SMDX_SUBJECT_REASON_CODE = 10;
726 
727     /**
728      * HTTP error
729      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
730      */
731     public static final int OPERATION_HTTP = 11;
732 
733     /**
734      * List of ErrorCode corresponding to {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE}
735      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
736      * @hide
737      */
738     @Retention(RetentionPolicy.SOURCE)
739     @IntDef(prefix = {"ERROR_"}, value = {
740             ERROR_CARRIER_LOCKED,
741             ERROR_INVALID_ACTIVATION_CODE,
742             ERROR_INVALID_CONFIRMATION_CODE,
743             ERROR_INCOMPATIBLE_CARRIER,
744             ERROR_EUICC_INSUFFICIENT_MEMORY,
745             ERROR_TIME_OUT,
746             ERROR_EUICC_MISSING,
747             ERROR_UNSUPPORTED_VERSION,
748             ERROR_SIM_MISSING,
749             ERROR_INSTALL_PROFILE,
750             ERROR_DISALLOWED_BY_PPR,
751             ERROR_ADDRESS_MISSING,
752             ERROR_CERTIFICATE_ERROR,
753             ERROR_NO_PROFILES_AVAILABLE,
754             ERROR_CONNECTION_ERROR,
755             ERROR_INVALID_RESPONSE,
756             ERROR_OPERATION_BUSY,
757     })
758     public @interface ErrorCode{}
759 
760     /**
761      * Operation such as downloading/switching to another profile failed due to device being
762      * carrier locked.
763      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
764      */
765     public static final int ERROR_CARRIER_LOCKED = 10000;
766 
767     /**
768      * The activation code(SGP.22 v2.2 section[4.1]) is invalid.
769      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
770      */
771     public static final int ERROR_INVALID_ACTIVATION_CODE = 10001;
772 
773     /**
774      * The confirmation code(SGP.22 v2.2 section[4.7]) is invalid.
775      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
776      */
777     public static final int ERROR_INVALID_CONFIRMATION_CODE = 10002;
778 
779     /**
780      * The profile's carrier is incompatible with the LPA.
781      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
782      */
783     public static final int ERROR_INCOMPATIBLE_CARRIER = 10003;
784 
785     /**
786      * There is no more space available on the eUICC for new profiles.
787      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
788      */
789     public static final int ERROR_EUICC_INSUFFICIENT_MEMORY = 10004;
790 
791     /**
792      * Timed out while waiting for an operation to complete. i.e restart, disable,
793      * switch reset etc.
794      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
795      */
796     public static final int ERROR_TIME_OUT = 10005;
797 
798     /**
799      * eUICC is missing or defective on the device.
800      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
801      */
802     public static final int ERROR_EUICC_MISSING = 10006;
803 
804     /**
805      * The eUICC card(hardware) version is incompatible with the software
806      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
807      */
808     public static final int ERROR_UNSUPPORTED_VERSION = 10007;
809 
810     /**
811      * No SIM card is available in the device.
812      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
813      */
814     public static final int ERROR_SIM_MISSING = 10008;
815 
816     /**
817      * Failure to load the profile onto the eUICC card. e.g
818      * 1. iccid of the profile already exists on the eUICC.
819      * 2. GSMA(.22 v2.2) Profile Install Result - installFailedDueToDataMismatch
820      * 3. operation was interrupted
821      * 4. SIMalliance error in PEStatus(SGP.22 v2.2 section 2.5.6.1)
822      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
823      */
824     public static final int ERROR_INSTALL_PROFILE = 10009;
825 
826     /**
827      * Failed to load profile onto eUICC due to Profile Policy Rules.
828      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
829      */
830     public static final int ERROR_DISALLOWED_BY_PPR = 10010;
831 
832 
833     /**
834      * Address is missing e.g SMDS/SMDP address is missing.
835      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
836      */
837     public static final int ERROR_ADDRESS_MISSING = 10011;
838 
839     /**
840      * Certificate needed for authentication is not valid or missing. E.g  SMDP/SMDS authentication
841      * failed.
842      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
843      */
844     public static final int ERROR_CERTIFICATE_ERROR = 10012;
845 
846 
847     /**
848      * No profiles available.
849      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
850      */
851     public static final int ERROR_NO_PROFILES_AVAILABLE = 10013;
852 
853     /**
854      * Failure to create a connection.
855      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
856      */
857     public static final int ERROR_CONNECTION_ERROR = 10014;
858 
859     /**
860      * Response format is invalid. e.g SMDP/SMDS response contains invalid json, header or/and ASN1.
861      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
862      */
863     public static final int ERROR_INVALID_RESPONSE = 10015;
864 
865     /**
866      * The operation is currently busy, try again later.
867      * @see #EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE for details
868      */
869     public static final int ERROR_OPERATION_BUSY = 10016;
870 
871     /**
872      * Failure due to target port is not supported.
873      * @see #switchToSubscription(int, int, PendingIntent)
874      */
875     public static final int ERROR_INVALID_PORT = 10017;
876 
877     /** Temporary failure to retrieve available memory because eUICC is not ready. */
878     @FlaggedApi(Flags.FLAG_ESIM_AVAILABLE_MEMORY)
879     public static final long EUICC_MEMORY_FIELD_UNAVAILABLE = -1L;
880 
881     /**
882      * Apps targeting on Android T and beyond will get exception whenever switchToSubscription
883      * without portIndex is called for disable subscription.
884      * @hide
885      */
886     @ChangeId
887     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.TIRAMISU)
888     public static final long SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE = 218393363L;
889 
890     /**
891      * With support for MEP(multiple enabled profile) in Android T, a SIM card can enable multiple
892      * profile on different port. If apps are not target SDK T yet and keep calling the
893      * switchToSubscription or download API without specifying the port index, we should
894      * keep the existing behaviour by always use port index 0 even the device itself has MEP eUICC,
895      * this is for carrier app's backward compatibility.
896      * @hide
897      */
898     @ChangeId
899     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.TIRAMISU)
900     public static final long SHOULD_RESOLVE_PORT_INDEX_FOR_APPS = 224562872L;
901 
902     /**
903      * Starting with Android U, a port is available if it is active without an enabled profile
904      * on it or calling app can activate a new profile on the selected port without any user
905      * interaction.
906      * @hide
907      */
908     @ChangeId
909     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
910     public static final long INACTIVE_PORT_AVAILABILITY_CHECK = 240273417L;
911 
912     private final Context mContext;
913     private int mCardId;
914 
915     /** @hide */
EuiccManager(Context context)916     public EuiccManager(Context context) {
917         mContext = context;
918         mCardId = getCardIdForDefaultEuicc();
919     }
920 
921     /** @hide */
EuiccManager(Context context, int cardId)922     private EuiccManager(Context context, int cardId) {
923         mContext = context;
924         mCardId = cardId;
925     }
926 
927     /**
928      * Create a new EuiccManager object pinned to the given card ID.
929      *
930      * @return an EuiccManager that uses the given card ID for all calls.
931      */
932     @NonNull
createForCardId(int cardId)933     public EuiccManager createForCardId(int cardId) {
934         return new EuiccManager(mContext, cardId);
935     }
936 
937     /**
938      * Whether embedded subscriptions are currently enabled.
939      *
940      * <p>Even on devices with the {@link PackageManager#FEATURE_TELEPHONY_EUICC} feature, embedded
941      * subscriptions may be turned off, e.g. because of a carrier restriction from an inserted
942      * physical SIM. Therefore, this runtime check should be used before accessing embedded
943      * subscription APIs.
944      *
945      * @return true if embedded subscriptions are currently enabled.
946      *
947      * @throws UnsupportedOperationException If the device does not have
948      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
949      */
isEnabled()950     public boolean isEnabled() {
951         // In the future, this may reach out to IEuiccController (if non-null) to check any dynamic
952         // restrictions.
953         return getIEuiccController() != null && refreshCardIdIfUninitialized();
954     }
955 
956     /**
957      * Returns the EID identifying the eUICC hardware.
958      *
959      * <p>Requires that the calling app has carrier privileges on the active subscription on the
960      * current eUICC. A calling app with carrier privileges for one eUICC may not necessarily have
961      * access to the EID of another eUICC.
962      *
963      * @return the EID. May be null if the eUICC is not ready.
964      *
965      * @throws UnsupportedOperationException If the device does not have
966      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
967      */
968     @Nullable
getEid()969     public String getEid() {
970         if (!isEnabled()) {
971             return null;
972         }
973         try {
974             return getIEuiccController().getEid(mCardId, mContext.getOpPackageName());
975         } catch (RemoteException e) {
976             throw e.rethrowFromSystemServer();
977         }
978     }
979 
980     /**
981      * Returns the available memory in bytes of the eUICC.
982      *
983      * @return the available memory in bytes. May be {@link #EUICC_MEMORY_FIELD_UNAVAILABLE} if the
984      *     eUICC is not ready. Check {@link #isEnabled} for more information.
985      * @throws UnsupportedOperationException If the device does not have
986      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC} or
987      *          device doesn't support querying this information from the eUICC.
988      */
989     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
990     @FlaggedApi(Flags.FLAG_ESIM_AVAILABLE_MEMORY)
991     @RequiresPermission(
992             anyOf = {
993                 Manifest.permission.READ_PHONE_STATE,
994                 Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
995                 "carrier privileges"
996             })
getAvailableMemoryInBytes()997     public long getAvailableMemoryInBytes() {
998         if (!isEnabled()) {
999             return EUICC_MEMORY_FIELD_UNAVAILABLE;
1000         }
1001         try {
1002             return getIEuiccController()
1003                     .getAvailableMemoryInBytes(mCardId, mContext.getOpPackageName());
1004         } catch (RemoteException e) {
1005             throw e.rethrowFromSystemServer();
1006         }
1007     }
1008 
1009     /**
1010      * Returns the current status of eUICC OTA.
1011      *
1012      * <p>Requires the {@link android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1013      *
1014      * @return the status of eUICC OTA. If the eUICC is not ready,
1015      *         {@link OtaStatus#EUICC_OTA_STATUS_UNAVAILABLE} will be returned.
1016      *
1017      * @throws UnsupportedOperationException If the device does not have
1018      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1019      * @hide
1020      */
1021     @SystemApi
1022     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
getOtaStatus()1023     public int getOtaStatus() {
1024         if (!isEnabled()) {
1025             return EUICC_OTA_STATUS_UNAVAILABLE;
1026         }
1027         try {
1028             return getIEuiccController().getOtaStatus(mCardId);
1029         } catch (RemoteException e) {
1030             throw e.rethrowFromSystemServer();
1031         }
1032     }
1033 
1034     /**
1035      * Attempt to download the given {@link DownloadableSubscription}.
1036      *
1037      * <p>Requires the {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS}
1038      * or the calling app must be authorized to manage both the currently-active
1039      * subscription on the
1040      * current eUICC and the subscription to be downloaded according to the subscription metadata.
1041      * Without the former, an {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR} will be
1042      * returned in the callback intent to prompt the user to accept the download.
1043      *
1044      * <p> Starting from Android {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM},
1045      * if the caller has the
1046      * {@code android.Manifest.permission#MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS} permission or
1047      * is a profile owner or device owner, then the downloaded subscription
1048      * will be managed by that caller.
1049      * In case the caller is device owner or profile owner of an organization-owned device, {@code
1050      * switchAfterDownload} can be set to true to automatically enable the subscription after
1051      * download. If the caller is a profile owner on non organization owned device
1052      * {@code switchAfterDownload} should be false otherwise the operation will fail with
1053      * {@link #EMBEDDED_SUBSCRIPTION_RESULT_ERROR}.
1054      *
1055      * <p>On a multi-active SIM device, requires the
1056      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission, or a calling app
1057      * only if the targeted eUICC does not currently have an active subscription or the calling app
1058      * is authorized to manage the active subscription on the target eUICC, and the calling app is
1059      * authorized to manage any active subscription on any SIM. Without it, an
1060      * {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR} will be returned in the callback
1061      * intent to prompt the user to accept the download. The caller should also be authorized to
1062      * manage the subscription to be downloaded.
1063      *
1064      * <p>If device support {@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP} and
1065      * switchAfterDownload is {@code true}, the subscription will be enabled on an esim port based
1066      * on the following selection rules:
1067      * <ul>
1068      *    <li>In SS(Single SIM) mode, if the embedded slot already has an active port, then download
1069      *    and enable the subscription on this port.
1070      *    <li>In SS mode, if the embedded slot is not active, then try to download and enable the
1071      *    subscription on the default port 0 of eUICC.
1072      *    <li>In DSDS mode, find first available port to download and enable the subscription.
1073      *    (see {@link #isSimPortAvailable(int)})
1074      *</ul>
1075      * If there is no available port, an {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR}
1076      * will be returned in the callback intent to prompt the user to disable an already-active
1077      * subscription.
1078      *
1079      * @param subscription the subscription to download.
1080      * @param switchAfterDownload if true, the profile will be activated upon successful download.
1081      * @param callbackIntent a PendingIntent to launch when the operation completes.
1082      *
1083      * @throws UnsupportedOperationException If the device does not have
1084      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1085      */
1086     @RequiresPermission(anyOf = {
1087             Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS,
1088             Manifest.permission.MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS})
downloadSubscription(DownloadableSubscription subscription, boolean switchAfterDownload, PendingIntent callbackIntent)1089     public void downloadSubscription(DownloadableSubscription subscription,
1090             boolean switchAfterDownload, PendingIntent callbackIntent) {
1091         if (!isEnabled()) {
1092             sendUnavailableError(callbackIntent);
1093             return;
1094         }
1095         try {
1096             getIEuiccController().downloadSubscription(mCardId, subscription, switchAfterDownload,
1097                     mContext.getOpPackageName(), null /* resolvedBundle */, callbackIntent);
1098         } catch (RemoteException e) {
1099             throw e.rethrowFromSystemServer();
1100         }
1101     }
1102 
1103     /**
1104      * Start an activity to resolve a user-resolvable error.
1105      *
1106      * <p>If an operation returns {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR}, this
1107      * method may be called to prompt the user to resolve the issue.
1108      *
1109      * <p>This method may only be called once for a particular error.
1110      *
1111      * @param activity the calling activity (which should be in the foreground).
1112      * @param requestCode an application-specific request code which will be provided to
1113      *     {@link Activity#onActivityResult} upon completion. Note that the operation may still be
1114      *     in progress when the resolution activity completes; it is not fully finished until the
1115      *     callback intent is triggered.
1116      * @param resultIntent the Intent provided to the initial callback intent which failed with
1117      *     {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR}.
1118      * @param callbackIntent a PendingIntent to launch when the operation completes. This is
1119      *     trigered upon completion of the original operation that required user resolution.
1120      * @throws android.content.IntentSender.SendIntentException if called more than once.
1121      */
startResolutionActivity(Activity activity, int requestCode, Intent resultIntent, PendingIntent callbackIntent)1122     public void startResolutionActivity(Activity activity, int requestCode, Intent resultIntent,
1123             PendingIntent callbackIntent) throws IntentSender.SendIntentException {
1124         PendingIntent resolutionIntent =
1125                 resultIntent.getParcelableExtra(EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_INTENT, android.app.PendingIntent.class);
1126         if (resolutionIntent == null) {
1127             throw new IllegalArgumentException("Invalid result intent");
1128         }
1129         Intent fillInIntent = new Intent();
1130         fillInIntent.putExtra(EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_CALLBACK_INTENT,
1131                 callbackIntent);
1132         activity.startIntentSenderForResult(resolutionIntent.getIntentSender(), requestCode,
1133                 fillInIntent, 0 /* flagsMask */, 0 /* flagsValues */, 0 /* extraFlags */);
1134     }
1135 
1136     /**
1137      * Continue an operation after the user resolves an error.
1138      *
1139      * <p>To be called by the LUI upon completion of a resolvable error flow.
1140      *
1141      * <p>Requires that the calling app has the
1142      * {@link android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1143      *
1144      * @param resolutionIntent The original intent used to start the LUI.
1145      * @param resolutionExtras Resolution-specific extras depending on the result of the resolution.
1146      *     For example, this may indicate whether the user has consented or may include the input
1147      *     they provided.
1148      *
1149      * @throws UnsupportedOperationException If the device does not have
1150      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1151      * @hide
1152      */
1153     @SystemApi
1154     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
continueOperation(Intent resolutionIntent, Bundle resolutionExtras)1155     public void continueOperation(Intent resolutionIntent, Bundle resolutionExtras) {
1156         if (!isEnabled()) {
1157             PendingIntent callbackIntent =
1158                     resolutionIntent.getParcelableExtra(
1159                             EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_CALLBACK_INTENT, android.app.PendingIntent.class);
1160             if (callbackIntent != null) {
1161                 sendUnavailableError(callbackIntent);
1162             }
1163             return;
1164         }
1165         try {
1166             getIEuiccController().continueOperation(mCardId, resolutionIntent, resolutionExtras);
1167         } catch (RemoteException e) {
1168             throw e.rethrowFromSystemServer();
1169         }
1170     }
1171 
1172     /**
1173      * Fills in the metadata for a DownloadableSubscription.
1174      *
1175      * <p>May be used in cases that a DownloadableSubscription was constructed to download a
1176      * profile, but the metadata for the profile is unknown (e.g. we only know the activation code).
1177      * The callback will be triggered with an Intent with
1178      * {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTION} set to the
1179      * downloadable subscription metadata upon success.
1180      *
1181      * <p>Requires that the calling app has the
1182      * {@link android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission. This is for
1183      * internal system use only.
1184      *
1185      * @param subscription the subscription which needs metadata filled in
1186      * @param callbackIntent a PendingIntent to launch when the operation completes.
1187      *
1188      * @throws UnsupportedOperationException If the device does not have
1189      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1190      * @hide
1191      */
1192     @SystemApi
1193     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
getDownloadableSubscriptionMetadata( DownloadableSubscription subscription, PendingIntent callbackIntent)1194     public void getDownloadableSubscriptionMetadata(
1195             DownloadableSubscription subscription, PendingIntent callbackIntent) {
1196         if (!isEnabled()) {
1197             sendUnavailableError(callbackIntent);
1198             return;
1199         }
1200         try {
1201             getIEuiccController().getDownloadableSubscriptionMetadata(mCardId, subscription,
1202                     mContext.getOpPackageName(), callbackIntent);
1203         } catch (RemoteException e) {
1204             throw e.rethrowFromSystemServer();
1205         }
1206     }
1207 
1208     /**
1209      * Gets metadata for subscription which are available for download on this device.
1210      *
1211      * <p>Subscriptions returned here may be passed to {@link #downloadSubscription}. They may have
1212      * been pre-assigned to this particular device, for example. The callback will be triggered with
1213      * an Intent with {@link #EXTRA_EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTIONS} set to the
1214      * list of available subscriptions upon success.
1215      *
1216      * <p>Requires that the calling app has the
1217      * {@link android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission. This is for
1218      * internal system use only.
1219      *
1220      * @param callbackIntent a PendingIntent to launch when the operation completes.
1221      *
1222      * @throws UnsupportedOperationException If the device does not have
1223      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1224      * @hide
1225      */
1226     @SystemApi
1227     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
getDefaultDownloadableSubscriptionList(PendingIntent callbackIntent)1228     public void getDefaultDownloadableSubscriptionList(PendingIntent callbackIntent) {
1229         if (!isEnabled()) {
1230             sendUnavailableError(callbackIntent);
1231             return;
1232         }
1233         try {
1234             getIEuiccController().getDefaultDownloadableSubscriptionList(mCardId,
1235                     mContext.getOpPackageName(), callbackIntent);
1236         } catch (RemoteException e) {
1237             throw e.rethrowFromSystemServer();
1238         }
1239     }
1240 
1241     /**
1242      * Returns information about the eUICC chip/device.
1243      *
1244      * @return the {@link EuiccInfo}. May be null if the eUICC is not ready.
1245      *
1246      * @throws UnsupportedOperationException If the device does not have
1247      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1248      */
1249     @Nullable
getEuiccInfo()1250     public EuiccInfo getEuiccInfo() {
1251         if (!isEnabled()) {
1252             return null;
1253         }
1254         try {
1255             return getIEuiccController().getEuiccInfo(mCardId);
1256         } catch (RemoteException e) {
1257             throw e.rethrowFromSystemServer();
1258         }
1259     }
1260 
1261     /**
1262      * Deletes the given subscription.
1263      *
1264      * <p>If this subscription is currently active, the device will first switch away from it onto
1265      * an "empty" subscription.
1266      *
1267      * <p>Requires that the calling app has carrier privileges according to the metadata of the
1268      * profile to be deleted, or the
1269      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1270      * Starting from Android {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, if the
1271      * caller is a device owner, profile owner, or holds the
1272      * {@code android.Manifest.permission#MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS} permission,
1273      * then the caller can delete a subscription that was downloaded by that caller.
1274      * If such a caller tries to delete any other subscription then the
1275      * operation will fail with {@link #EMBEDDED_SUBSCRIPTION_RESULT_ERROR}.
1276      *
1277      * @param subscriptionId the ID of the subscription to delete.
1278      * @param callbackIntent a PendingIntent to launch when the operation completes.
1279      *
1280      * @throws UnsupportedOperationException If the device does not have
1281      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1282      */
1283     @RequiresPermission(anyOf = {
1284             Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS,
1285             Manifest.permission.MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS})
deleteSubscription(int subscriptionId, PendingIntent callbackIntent)1286     public void deleteSubscription(int subscriptionId, PendingIntent callbackIntent) {
1287         if (!isEnabled()) {
1288             sendUnavailableError(callbackIntent);
1289             return;
1290         }
1291         try {
1292             getIEuiccController().deleteSubscription(mCardId,
1293                     subscriptionId, mContext.getOpPackageName(), callbackIntent);
1294         } catch (RemoteException e) {
1295             throw e.rethrowFromSystemServer();
1296         }
1297     }
1298 
1299     /**
1300      * Switch to (enable) the given subscription.
1301      *
1302      * <p>Requires the {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission,
1303      * or the calling app must be authorized to manage both the currently-active subscription and
1304      * the subscription to be enabled according to the subscription metadata. Without the former,
1305      * an {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR} will be returned in the callback
1306      * intent to prompt the user to accept the download.
1307      *
1308      * <p>On a multi-active SIM device, requires the
1309      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission, or a calling app
1310      *  only if the targeted eUICC does not currently have an active subscription or the calling app
1311      * is authorized to manage the active subscription on the target eUICC, and the calling app is
1312      * authorized to manage any active subscription on any SIM. Without it, an
1313      * {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR} will be returned in the callback
1314      * intent to prompt the user to accept the download. The caller should also be authorized to
1315      * manage the subscription to be enabled.
1316      *
1317      * <p> From Android T, devices might support {@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP},
1318      * the subscription can be installed on different port from the eUICC. Calling apps with
1319      * carrier privilege (see {@link TelephonyManager#hasCarrierPrivileges}) over the currently
1320      * active subscriptions can use {@link #switchToSubscription(int, int, PendingIntent)} to
1321      * specify which port to enable the subscription. Otherwise, use this API to enable the
1322      * subscription on the eUICC and the platform will internally resolve a port based on following
1323      * rules:
1324      * <ul>
1325      *    <li>always use the default port 0 is eUICC does not support MEP or the apps are
1326      *    not targeting on Android T.
1327      *    <li>In SS(Single SIM) mode, if the embedded slot already has an active port, then enable
1328      *    the subscription on this port.
1329      *    <li>In SS mode, if the embedded slot is not active, then try to enable the subscription on
1330      *    the default port 0 of eUICC.
1331      *    <li>In DSDS mode, find first available port to enable the subscription.
1332      *    (see {@link #isSimPortAvailable(int)})
1333      *</ul>
1334      * If there is no available port, an {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR}
1335      * will be returned in the callback intent to prompt the user to disable an already-active
1336      * subscription.
1337      *
1338      * @param subscriptionId the ID of the subscription to enable. May be
1339      *     {@link android.telephony.SubscriptionManager#INVALID_SUBSCRIPTION_ID} to deactivate the
1340      *     current profile without activating another profile to replace it. Calling apps targeting
1341      *     on android T must use {@link #switchToSubscription(int, int, PendingIntent)} API for
1342      *     disable profile, port index can be found from {@link SubscriptionInfo#getPortIndex()}.
1343      *     If it's a disable operation, requires the
1344      *     {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission, or the
1345      *     calling app must be authorized to manage the active subscription on the target eUICC.
1346      * @param callbackIntent a PendingIntent to launch when the operation completes.
1347      *
1348      * @throws UnsupportedOperationException If the device does not have
1349      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1350      */
1351     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
switchToSubscription(int subscriptionId, PendingIntent callbackIntent)1352     public void switchToSubscription(int subscriptionId, PendingIntent callbackIntent) {
1353         if (!isEnabled()) {
1354             sendUnavailableError(callbackIntent);
1355             return;
1356         }
1357         try {
1358             if (subscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID
1359                      && getIEuiccController().isCompatChangeEnabled(mContext.getOpPackageName(),
1360                      SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE)) {
1361                 // Apps targeting on Android T and beyond will get exception whenever
1362                 // switchToSubscription without portIndex is called with INVALID_SUBSCRIPTION_ID.
1363                 Log.e(TAG, "switchToSubscription without portIndex is not allowed for"
1364                         + " disable operation");
1365                 throw new IllegalArgumentException("Must use switchToSubscription with portIndex"
1366                         + " API for disable operation");
1367             }
1368             getIEuiccController().switchToSubscription(mCardId,
1369                     subscriptionId, mContext.getOpPackageName(), callbackIntent);
1370         } catch (RemoteException e) {
1371             throw e.rethrowFromSystemServer();
1372         }
1373     }
1374 
1375     /**
1376      * Switch to (enable) the given subscription.
1377      *
1378      * <p> Requires the {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission,
1379      * or the caller must be having both the carrier privileges
1380      * (see {@link TelephonyManager#hasCarrierPrivileges}) over any currently active subscriptions
1381      * and the subscription to be enabled according to the subscription metadata.
1382      * Without the former permissions, an SecurityException is thrown.
1383      *
1384      * <p> If the caller is passing invalid port index,
1385      * an {@link #EMBEDDED_SUBSCRIPTION_RESULT_ERROR} with detailed error code
1386      * {@link #ERROR_INVALID_PORT} will be returned. The port index is invalid if one of the
1387      * following requirements is met:
1388      * <ul>
1389      *     <li>index is beyond the range of {@link UiccCardInfo#getPorts()}.
1390      *     <li>In SS(Single SIM) mode, the embedded slot already has an active port with different
1391      *     port index.
1392      *     <li>In DSDS mode, if the psim slot is active and the embedded slot already has an active
1393      *     empty port with different port index.
1394      * </ul>
1395      *
1396      * <p> Depending on the target port and permission check,
1397      * an {@link #EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR} might be returned to the callback
1398      * intent to prompt the user to authorize before the switch.
1399      *
1400      * @param subscriptionId the ID of the subscription to enable. May be
1401      *     {@link android.telephony.SubscriptionManager#INVALID_SUBSCRIPTION_ID} to deactivate the
1402      *     current profile without activating another profile to replace it. If it's a disable
1403      *     operation, requires the {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS}
1404      *     permission, or the calling app must be authorized to manage the active subscription on
1405      *     the target eUICC. From Android T, multiple enabled profiles is supported. Calling apps
1406      *     targeting on android T must use {@link #switchToSubscription(int, int, PendingIntent)}
1407      *     API for disable profile, port index can be found from
1408      *     {@link SubscriptionInfo#getPortIndex()}.
1409      * @param portIndex the index of the port to target for the enabled subscription
1410      * @param callbackIntent a PendingIntent to launch when the operation completes.
1411      *
1412      * @throws UnsupportedOperationException If the device does not have
1413      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1414      */
1415     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
switchToSubscription(int subscriptionId, int portIndex, @NonNull PendingIntent callbackIntent)1416     public void switchToSubscription(int subscriptionId, int portIndex,
1417             @NonNull PendingIntent callbackIntent) {
1418         if (!isEnabled()) {
1419             sendUnavailableError(callbackIntent);
1420             return;
1421         }
1422         try {
1423             boolean canWriteEmbeddedSubscriptions = mContext.checkCallingOrSelfPermission(
1424                     Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
1425                     == PackageManager.PERMISSION_GRANTED;
1426             // If the caller is not privileged caller and does not have the carrier privilege over
1427             // any active subscription, do not continue.
1428             if (!canWriteEmbeddedSubscriptions && !getIEuiccController()
1429                     .hasCarrierPrivilegesForPackageOnAnyPhone(mContext.getOpPackageName())) {
1430                 Log.e(TAG, "Not permitted to use switchToSubscription with portIndex");
1431                 throw new SecurityException(
1432                         "Must have carrier privileges to use switchToSubscription with portIndex");
1433             }
1434             getIEuiccController().switchToSubscriptionWithPort(mCardId,
1435                     subscriptionId, portIndex, mContext.getOpPackageName(), callbackIntent);
1436         } catch (RemoteException e) {
1437             throw e.rethrowFromSystemServer();
1438         }
1439     }
1440 
1441     /**
1442      * Update the nickname for the given subscription.
1443      *
1444      * <p>Requires that the calling app has carrier privileges according to the metadata of the
1445      * profile to be updated, or the
1446      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1447      *
1448      * @param subscriptionId the ID of the subscription to update.
1449      * @param nickname the new nickname to apply.
1450      * @param callbackIntent a PendingIntent to launch when the operation completes.
1451      *
1452      * @throws UnsupportedOperationException If the device does not have
1453      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1454      */
1455     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
updateSubscriptionNickname( int subscriptionId, @Nullable String nickname, @NonNull PendingIntent callbackIntent)1456     public void updateSubscriptionNickname(
1457             int subscriptionId, @Nullable String nickname, @NonNull PendingIntent callbackIntent) {
1458         if (!isEnabled()) {
1459             sendUnavailableError(callbackIntent);
1460             return;
1461         }
1462         try {
1463             getIEuiccController().updateSubscriptionNickname(mCardId,
1464                     subscriptionId, nickname, mContext.getOpPackageName(), callbackIntent);
1465         } catch (RemoteException e) {
1466             throw e.rethrowFromSystemServer();
1467         }
1468     }
1469 
1470     /**
1471      * Erase all operational subscriptions and reset the eUICC.
1472      *
1473      * <p>Requires that the calling app has the
1474      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1475      *
1476      * @param callbackIntent a PendingIntent to launch when the operation completes.
1477      *
1478      * @deprecated From R, callers should specify a flag for specific set of subscriptions to erase
1479      * and use {@link #eraseSubscriptions(int, PendingIntent)} instead
1480      *
1481      * @throws UnsupportedOperationException If the device does not have
1482      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1483      * @hide
1484      */
1485     @SystemApi
1486     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
1487     @Deprecated
eraseSubscriptions(@onNull PendingIntent callbackIntent)1488     public void eraseSubscriptions(@NonNull PendingIntent callbackIntent) {
1489         if (!isEnabled()) {
1490             sendUnavailableError(callbackIntent);
1491             return;
1492         }
1493         try {
1494             getIEuiccController().eraseSubscriptions(mCardId, callbackIntent);
1495         } catch (RemoteException e) {
1496             throw e.rethrowFromSystemServer();
1497         }
1498     }
1499 
1500     /**
1501      * Erase all specific subscriptions and reset the eUICC.
1502      *
1503      * <p>Requires that the calling app has the
1504      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1505      *
1506      * @param options flag indicating specific set of subscriptions to erase
1507      * @param callbackIntent a PendingIntent to launch when the operation completes.
1508      *
1509      * @throws UnsupportedOperationException If the device does not have
1510      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1511      * @hide
1512      */
1513     @SystemApi
1514     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
eraseSubscriptions( @esetOption int options, @NonNull PendingIntent callbackIntent)1515     public void eraseSubscriptions(
1516             @ResetOption int options, @NonNull PendingIntent callbackIntent) {
1517         if (!isEnabled()) {
1518             sendUnavailableError(callbackIntent);
1519             return;
1520         }
1521         try {
1522             getIEuiccController().eraseSubscriptionsWithOptions(mCardId, options, callbackIntent);
1523         } catch (RemoteException e) {
1524             throw e.rethrowFromSystemServer();
1525         }
1526     }
1527 
1528     /**
1529      * Ensure that subscriptions will be retained on the next factory reset.
1530      *
1531      * <p>By default, all subscriptions on the eUICC are erased the first time a device boots (ever
1532      * and after factory resets). This ensures that the data is wiped after a factory reset is
1533      * performed via fastboot or recovery mode, as these modes do not support the necessary radio
1534      * communication needed to wipe the eSIM.
1535      *
1536      * <p>However, this method may be called right before a factory reset issued via settings when
1537      * the user elects to retain subscriptions. Doing so will mark them for retention so that they
1538      * are not cleared after the ensuing reset.
1539      *
1540      * <p>Requires that the calling app has the {@link android.Manifest.permission#MASTER_CLEAR}
1541      * permission. This is for internal system use only.
1542      *
1543      * @param callbackIntent a PendingIntent to launch when the operation completes.
1544      * @hide
1545      */
retainSubscriptionsForFactoryReset(PendingIntent callbackIntent)1546     public void retainSubscriptionsForFactoryReset(PendingIntent callbackIntent) {
1547         if (!isEnabled()) {
1548             sendUnavailableError(callbackIntent);
1549             return;
1550         }
1551         try {
1552             getIEuiccController().retainSubscriptionsForFactoryReset(mCardId, callbackIntent);
1553         } catch (RemoteException e) {
1554             throw e.rethrowFromSystemServer();
1555         }
1556     }
1557 
1558     /**
1559      * Sets the supported countries for eUICC.
1560      *
1561      * <p>Requires that the calling app has the
1562      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1563      *
1564      * <p>The supported country list will be replaced by {@code supportedCountries}. For how we
1565      * determine whether a country is supported please check {@link #isSupportedCountry}.
1566      *
1567      * @param supportedCountries is a list of strings contains country ISO codes in uppercase.
1568      *
1569      * @throws UnsupportedOperationException If the device does not have
1570      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1571      * @hide
1572      */
1573     @SystemApi
1574     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
setSupportedCountries(@onNull List<String> supportedCountries)1575     public void setSupportedCountries(@NonNull List<String> supportedCountries) {
1576         if (!isEnabled()) {
1577             return;
1578         }
1579         try {
1580             getIEuiccController().setSupportedCountries(
1581                     true /* isSupported */,
1582                     supportedCountries.stream()
1583                         .map(String::toUpperCase).collect(Collectors.toList()));
1584         } catch (RemoteException e) {
1585             throw e.rethrowFromSystemServer();
1586         }
1587     }
1588 
1589     /**
1590      * Sets the unsupported countries for eUICC.
1591      *
1592      * <p>Requires that the calling app has the
1593      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1594      *
1595      * <p>The unsupported country list will be replaced by {@code unsupportedCountries}. For how we
1596      * determine whether a country is supported please check {@link #isSupportedCountry}.
1597      *
1598      * @param unsupportedCountries is a list of strings contains country ISO codes in uppercase.
1599      *
1600      * @throws UnsupportedOperationException If the device does not have
1601      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1602      * @hide
1603      */
1604     @SystemApi
1605     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
setUnsupportedCountries(@onNull List<String> unsupportedCountries)1606     public void setUnsupportedCountries(@NonNull List<String> unsupportedCountries) {
1607         if (!isEnabled()) {
1608             return;
1609         }
1610         try {
1611             getIEuiccController().setSupportedCountries(
1612                     false /* isSupported */,
1613                     unsupportedCountries.stream()
1614                         .map(String::toUpperCase).collect(Collectors.toList()));
1615         } catch (RemoteException e) {
1616             throw e.rethrowFromSystemServer();
1617         }
1618     }
1619 
1620     /**
1621      * Gets the supported countries for eUICC.
1622      *
1623      * <p>Requires that the calling app has the
1624      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1625      *
1626      * @return list of strings contains country ISO codes in uppercase.
1627      *
1628      * @throws UnsupportedOperationException If the device does not have
1629      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1630      * @hide
1631      */
1632     @SystemApi
1633     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
1634     @NonNull
getSupportedCountries()1635     public List<String> getSupportedCountries() {
1636         if (!isEnabled()) {
1637             return Collections.emptyList();
1638         }
1639         try {
1640             return getIEuiccController().getSupportedCountries(true /* isSupported */);
1641         } catch (RemoteException e) {
1642             throw e.rethrowFromSystemServer();
1643         }
1644     }
1645 
1646     /**
1647      * Gets the unsupported countries for eUICC.
1648      *
1649      * <p>Requires that the calling app has the
1650      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
1651      *
1652      * @return list of strings contains country ISO codes in uppercase.
1653      *
1654      * @throws UnsupportedOperationException If the device does not have
1655      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1656      * @hide
1657      */
1658     @SystemApi
1659     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
1660     @NonNull
getUnsupportedCountries()1661     public List<String> getUnsupportedCountries() {
1662         if (!isEnabled()) {
1663             return Collections.emptyList();
1664         }
1665         try {
1666             return getIEuiccController().getSupportedCountries(false /* isSupported */);
1667         } catch (RemoteException e) {
1668             throw e.rethrowFromSystemServer();
1669         }
1670     }
1671 
1672     /**
1673      * Returns whether the given country supports eUICC.
1674      *
1675      * <p>Supported country list has a higher prority than unsupported country list. If the
1676      * supported country list is not empty, {@code countryIso} will be considered as supported when
1677      * it exists in the supported country list. Otherwise {@code countryIso} is not supported. If
1678      * the supported country list is empty, {@code countryIso} will be considered as supported if it
1679      * does not exist in the unsupported country list. Otherwise {@code countryIso} is not
1680      * supported. If both supported and unsupported country lists are empty, then all countries are
1681      * consider be supported. For how to set supported and unsupported country list, please check
1682      * {@link #setSupportedCountries} and {@link #setUnsupportedCountries}.
1683      *
1684      * @param countryIso should be the ISO-3166 country code is provided in uppercase 2 character
1685      * format.
1686      * @return whether the given country supports eUICC or not.
1687      *
1688      * @throws UnsupportedOperationException If the device does not have
1689      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1690      * @hide
1691      */
1692     @SystemApi
1693     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
isSupportedCountry(@onNull String countryIso)1694     public boolean isSupportedCountry(@NonNull String countryIso) {
1695         if (!isEnabled()) {
1696             return false;
1697         }
1698         try {
1699             return getIEuiccController().isSupportedCountry(countryIso.toUpperCase(Locale.ROOT));
1700         } catch (RemoteException e) {
1701             throw e.rethrowFromSystemServer();
1702         }
1703     }
1704 
1705     /**
1706      * Refreshes the cardId if its uninitialized, and returns whether we should continue the
1707      * operation.
1708      * <p>
1709      * Note that after a successful refresh, the mCardId may be TelephonyManager.UNSUPPORTED_CARD_ID
1710      * on older HALs. For backwards compatability, we continue to the LPA and let it decide which
1711      * card to use.
1712      */
refreshCardIdIfUninitialized()1713     private boolean refreshCardIdIfUninitialized() {
1714         // Refresh mCardId if its UNINITIALIZED_CARD_ID
1715         if (mCardId == TelephonyManager.UNINITIALIZED_CARD_ID) {
1716             mCardId = getCardIdForDefaultEuicc();
1717         }
1718         return mCardId != TelephonyManager.UNINITIALIZED_CARD_ID;
1719     }
1720 
sendUnavailableError(PendingIntent callbackIntent)1721     private static void sendUnavailableError(PendingIntent callbackIntent) {
1722         try {
1723             callbackIntent.send(EMBEDDED_SUBSCRIPTION_RESULT_ERROR);
1724         } catch (PendingIntent.CanceledException e) {
1725             // Caller canceled the callback; do nothing.
1726         }
1727     }
1728 
getIEuiccController()1729     private static IEuiccController getIEuiccController() {
1730         return IEuiccController.Stub.asInterface(
1731                 TelephonyFrameworkInitializer
1732                         .getTelephonyServiceManager()
1733                         .getEuiccControllerService()
1734                         .get());
1735     }
1736 
getCardIdForDefaultEuicc()1737     private int getCardIdForDefaultEuicc() {
1738         int cardId = TelephonyManager.UNINITIALIZED_CARD_ID;
1739 
1740         if (Flags.enforceTelephonyFeatureMappingForPublicApis()) {
1741             PackageManager pm = mContext.getPackageManager();
1742             if (pm != null && pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_EUICC)) {
1743                 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1744                 cardId = tm.getCardIdForDefaultEuicc();
1745             }
1746         } else {
1747             TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1748             cardId = tm.getCardIdForDefaultEuicc();
1749         }
1750 
1751         return cardId;
1752     }
1753 
1754     /**
1755      * Returns whether the passing portIndex is available.
1756      * A port is available if it is active without enabled profile on it or
1757      * calling app has carrier privilege over the profile installed on the selected port.
1758      *
1759      * <p> From Android U, a port is available if it is active without an enabled profile on it or
1760      * calling app can activate a new profile on the selected port without any user interaction.
1761      *
1762      * Always returns false if the cardId is a physical card.
1763      *
1764      * @param portIndex is an enumeration of the ports available on the UICC.
1765      * @return {@code true} if port is available
1766      *
1767      * @throws UnsupportedOperationException If the device does not have
1768      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1769      */
isSimPortAvailable(int portIndex)1770     public boolean isSimPortAvailable(int portIndex) {
1771         try {
1772             return getIEuiccController().isSimPortAvailable(mCardId, portIndex,
1773                     mContext.getOpPackageName());
1774         } catch (RemoteException e) {
1775             throw e.rethrowFromSystemServer();
1776         }
1777     }
1778 
1779     /**
1780      * Sets the supported carrier ids for pSIM conversion.
1781      *
1782      * <p>Any existing pSIM conversion supported carrier list will be replaced
1783      * by the {@code carrierIds} set here.
1784      *
1785      * @param carrierIds is a list of carrierIds that supports pSIM conversion
1786      *
1787      * @throws UnsupportedOperationException If the device does not have
1788      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1789      * @throws IllegalStateException if this method is called when {@link #isEnabled} is false.
1790      * @hide
1791      */
1792     @FlaggedApi(Flags.FLAG_SUPPORT_PSIM_TO_ESIM_CONVERSION)
1793     @SystemApi
1794     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
setPsimConversionSupportedCarriers(@onNull Set<Integer> carrierIds)1795     public void setPsimConversionSupportedCarriers(@NonNull Set<Integer> carrierIds) {
1796         if (!isEnabled()) {
1797             throw new IllegalStateException("Euicc is not enabled");
1798         }
1799         try {
1800             int[] arr = carrierIds.stream().mapToInt(Integer::intValue).toArray();
1801             getIEuiccController().setPsimConversionSupportedCarriers(arr);
1802         } catch (RemoteException e) {
1803             throw e.rethrowAsRuntimeException();
1804         }
1805     }
1806 
1807     /**
1808      * Returns whether the given carrier id supports pSIM conversion or not.
1809      *
1810      * @param carrierId to check whether pSIM conversion is supported or not
1811      * @return whether the given carrier id supports pSIM conversion or not,
1812      *         or false if {@link #isEnabled} is false
1813      *
1814      * @throws UnsupportedOperationException If the device does not have
1815      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
1816      * @hide
1817      */
1818     @FlaggedApi(Flags.FLAG_SUPPORT_PSIM_TO_ESIM_CONVERSION)
1819     @SystemApi
1820     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
isPsimConversionSupported(int carrierId)1821     public boolean isPsimConversionSupported(int carrierId) {
1822         if (!isEnabled()) {
1823             return false;
1824         }
1825         try {
1826             return getIEuiccController().isPsimConversionSupported(carrierId);
1827         } catch (RemoteException e) {
1828             throw e.rethrowAsRuntimeException();
1829         }
1830     }
1831 }
1832