1 /*
2  * Copyright (C) 2010 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 
17 
18 package android.hardware.usb;
19 
20 import static android.hardware.usb.UsbPortStatus.DATA_STATUS_DISABLED_FORCE;
21 
22 import android.Manifest;
23 import android.annotation.CallbackExecutor;
24 import android.annotation.IntDef;
25 import android.annotation.LongDef;
26 import android.annotation.NonNull;
27 import android.annotation.Nullable;
28 import android.annotation.RequiresFeature;
29 import android.annotation.RequiresPermission;
30 import android.annotation.SdkConstant;
31 import android.annotation.SdkConstant.SdkConstantType;
32 import android.annotation.SystemApi;
33 import android.annotation.SystemService;
34 import android.app.PendingIntent;
35 import android.compat.annotation.UnsupportedAppUsage;
36 import android.content.ComponentName;
37 import android.content.Context;
38 import android.content.pm.PackageManager;
39 import android.content.pm.PackageManager.NameNotFoundException;
40 import android.hardware.usb.gadget.GadgetFunction;
41 import android.hardware.usb.gadget.UsbSpeed;
42 import android.os.Binder;
43 import android.os.Build;
44 import android.os.Bundle;
45 import android.os.ParcelFileDescriptor;
46 import android.os.Process;
47 import android.os.RemoteException;
48 import android.os.SystemProperties;
49 import android.util.ArrayMap;
50 import android.util.Log;
51 import android.util.Slog;
52 
53 import com.android.internal.annotations.GuardedBy;
54 
55 import java.util.ArrayList;
56 import java.util.Collections;
57 import java.util.HashMap;
58 import java.util.List;
59 import java.util.Map;
60 import java.util.Objects;
61 import java.util.StringJoiner;
62 import java.util.concurrent.Executor;
63 import java.util.concurrent.atomic.AtomicInteger;
64 
65 /**
66  * This class allows you to access the state of USB and communicate with USB devices.
67  * Currently only host mode is supported in the public API.
68  *
69  * <div class="special reference">
70  * <h3>Developer Guides</h3>
71  * <p>For more information about communicating with USB hardware, read the
72  * <a href="{@docRoot}guide/topics/connectivity/usb/index.html">USB developer guide</a>.</p>
73  * </div>
74  */
75 @SystemService(Context.USB_SERVICE)
76 public class UsbManager {
77     private static final String TAG = "UsbManager";
78 
79     /**
80      * Broadcast Action:  A sticky broadcast for USB state change events when in device mode.
81      *
82      * This is a sticky broadcast for clients that includes USB connected/disconnected state,
83      * <ul>
84      * <li> {@link #USB_CONNECTED} boolean indicating whether USB is connected or disconnected.
85      * <li> {@link #USB_HOST_CONNECTED} boolean indicating whether USB is connected or
86      *     disconnected as host.
87      * <li> {@link #USB_CONFIGURED} boolean indicating whether USB is configured.
88      * currently zero if not configured, one for configured.
89      * <li> {@link #USB_FUNCTION_ADB} boolean extra indicating whether the
90      * adb function is enabled
91      * <li> {@link #USB_FUNCTION_RNDIS} boolean extra indicating whether the
92      * RNDIS ethernet function is enabled
93      * <li> {@link #USB_FUNCTION_MTP} boolean extra indicating whether the
94      * MTP function is enabled
95      * <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the
96      * PTP function is enabled
97      * <li> {@link #USB_FUNCTION_ACCESSORY} boolean extra indicating whether the
98      * accessory function is enabled
99      * <li> {@link #USB_FUNCTION_AUDIO_SOURCE} boolean extra indicating whether the
100      * audio source function is enabled
101      * <li> {@link #USB_FUNCTION_MIDI} boolean extra indicating whether the
102      * MIDI function is enabled
103      * <li> {@link #USB_FUNCTION_UVC} boolean extra indicating whether the
104      * UVC function is enabled
105      * </ul>
106      * If the sticky intent has not been found, that indicates USB is disconnected,
107      * USB is not configured, MTP function is enabled, and all the other functions are disabled.
108      *
109      * @hide
110      */
111     @SystemApi
112     public static final String ACTION_USB_STATE =
113             "android.hardware.usb.action.USB_STATE";
114 
115     /**
116      * Broadcast Action: A broadcast for USB port changes.
117      *
118      * This intent is sent when a USB port is added, removed, or changes state.
119      *
120      * @hide
121      */
122     @SystemApi
123     @RequiresPermission(Manifest.permission.MANAGE_USB)
124     public static final String ACTION_USB_PORT_CHANGED =
125             "android.hardware.usb.action.USB_PORT_CHANGED";
126 
127     /**
128      * Broadcast Action: A broadcast for USB compliance warning changes.
129      *
130      * This intent is sent when a port partner's
131      * (USB power source/cable/accessory) compliance warnings change state.
132      *
133      * @hide
134      */
135     @SystemApi
136     @RequiresPermission(Manifest.permission.MANAGE_USB)
137     public static final String ACTION_USB_PORT_COMPLIANCE_CHANGED =
138             "android.hardware.usb.action.USB_PORT_COMPLIANCE_CHANGED";
139 
140     /**
141      * Activity intent sent when user attaches a USB device.
142      *
143      * This intent is sent when a USB device is attached to the USB bus when in host mode.
144      * <ul>
145      * <li> {@link #EXTRA_DEVICE} containing the {@link android.hardware.usb.UsbDevice}
146      * for the attached device
147      * </ul>
148      */
149     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
150     public static final String ACTION_USB_DEVICE_ATTACHED =
151             "android.hardware.usb.action.USB_DEVICE_ATTACHED";
152 
153     /**
154      * Broadcast Action:  A broadcast for USB device detached event.
155      *
156      * This intent is sent when a USB device is detached from the USB bus when in host mode.
157      * <ul>
158      * <li> {@link #EXTRA_DEVICE} containing the {@link android.hardware.usb.UsbDevice}
159      * for the detached device
160      * </ul>
161      */
162     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
163     public static final String ACTION_USB_DEVICE_DETACHED =
164             "android.hardware.usb.action.USB_DEVICE_DETACHED";
165 
166     /**
167      * Activity intent sent when user attaches a USB accessory.
168      *
169      * <ul>
170      * <li> {@link #EXTRA_ACCESSORY} containing the {@link android.hardware.usb.UsbAccessory}
171      * for the attached accessory
172      * </ul>
173      */
174     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
175     public static final String ACTION_USB_ACCESSORY_ATTACHED =
176             "android.hardware.usb.action.USB_ACCESSORY_ATTACHED";
177 
178     /**
179      * Broadcast Action:  A broadcast for USB accessory detached event.
180      *
181      * This intent is sent when a USB accessory is detached.
182      * <ul>
183      * <li> {@link #EXTRA_ACCESSORY} containing the {@link UsbAccessory}
184      * for the attached accessory that was detached
185      * </ul>
186      */
187     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
188     public static final String ACTION_USB_ACCESSORY_DETACHED =
189             "android.hardware.usb.action.USB_ACCESSORY_DETACHED";
190 
191     /**
192      * Broadcast Action:  A broadcast for USB accessory handshaking information delivery
193      *
194      * This intent is sent when a USB accessory connect attempt
195      *
196      * <p>For more information about communicating with USB accessory handshake, refer to
197      * <a href="https://source.android.com/devices/accessories/aoa">AOA</a> developer guide.</p>
198      *
199      * @hide
200      */
201     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
202     @SystemApi
203     @RequiresPermission(Manifest.permission.MANAGE_USB)
204     public static final String ACTION_USB_ACCESSORY_HANDSHAKE =
205             "android.hardware.usb.action.USB_ACCESSORY_HANDSHAKE";
206 
207     /**
208      * Boolean extra indicating whether USB is connected or disconnected.
209      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
210      *
211      * @hide
212      */
213     @SystemApi
214     public static final String USB_CONNECTED = "connected";
215 
216     /**
217      * Boolean extra indicating whether USB is connected or disconnected as host.
218      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
219      *
220      * @hide
221      */
222     public static final String USB_HOST_CONNECTED = "host_connected";
223 
224     /**
225      * Boolean extra indicating whether USB is configured.
226      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
227      *
228      * @hide
229      */
230     @SystemApi
231     public static final String USB_CONFIGURED = "configured";
232 
233     /**
234      * Boolean extra indicating whether confidential user data, such as photos, should be
235      * made available on the USB connection. This variable will only be set when the user
236      * has explicitly asked for this data to be unlocked.
237      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
238      *
239      * @hide
240      */
241     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
242     public static final String USB_DATA_UNLOCKED = "unlocked";
243 
244     /**
245      * A placeholder indicating that no USB function is being specified.
246      * Used for compatibility with old init scripts to indicate no functions vs. charging function.
247      *
248      * @hide
249      */
250     @UnsupportedAppUsage
251     public static final String USB_FUNCTION_NONE = "none";
252 
253     /**
254      * Name of the adb USB function.
255      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
256      *
257      * @hide
258      */
259     public static final String USB_FUNCTION_ADB = "adb";
260 
261     /**
262      * Name of the RNDIS ethernet USB function.
263      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
264      *
265      * @hide
266      */
267     @SystemApi
268     public static final String USB_FUNCTION_RNDIS = "rndis";
269 
270     /**
271      * Name of the MTP USB function.
272      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
273      *
274      * @hide
275      */
276     public static final String USB_FUNCTION_MTP = "mtp";
277 
278     /**
279      * Name of the PTP USB function.
280      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
281      *
282      * @hide
283      */
284     public static final String USB_FUNCTION_PTP = "ptp";
285 
286     /**
287      * Name of the audio source USB function.
288      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
289      *
290      * @hide
291      */
292     public static final String USB_FUNCTION_AUDIO_SOURCE = "audio_source";
293 
294     /**
295      * Name of the MIDI USB function.
296      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
297      *
298      * @hide
299      */
300     public static final String USB_FUNCTION_MIDI = "midi";
301 
302     /**
303      * Name of the Accessory USB function.
304      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
305      *
306      * @hide
307      */
308     public static final String USB_FUNCTION_ACCESSORY = "accessory";
309 
310     /**
311      * Name of the NCM USB function.
312      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
313      *
314      * @hide
315      */
316     @SystemApi
317     public static final String USB_FUNCTION_NCM = "ncm";
318 
319     /**
320      * Name of the UVC USB function.
321      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
322      *
323      * @hide
324      */
325     public static final String USB_FUNCTION_UVC = "uvc";
326 
327     /**
328      * Name of Gadget Hal Not Present;
329      *
330      * @hide
331      */
332     public static final String GADGET_HAL_UNKNOWN = "unknown";
333 
334     /**
335      * Name of the USB Gadget Hal Version v1.0;
336      *
337      * @hide
338      */
339     public static final String GADGET_HAL_VERSION_1_0 = "V1_0";
340 
341     /**
342      * Name of the USB Gadget Hal Version v1.1;
343      *
344      * @hide
345      */
346     public static final String GADGET_HAL_VERSION_1_1 = "V1_1";
347 
348     /**
349      * Name of the USB Gadget Hal Version v1.2;
350      *
351      * @hide
352      */
353     public static final String GADGET_HAL_VERSION_1_2 = "V1_2";
354 
355     /**
356      * Name of the USB Gadget Hal Version v2.0;
357      *
358      * @hide
359      */
360     public static final String GADGET_HAL_VERSION_2_0 = "V2_0";
361 
362     /**
363      * Name of extra for {@link #ACTION_USB_PORT_CHANGED}
364      * containing the {@link UsbPort} object for the port.
365      *
366      * @hide
367      */
368     public static final String EXTRA_PORT = "port";
369 
370     /**
371      * Name of extra for {@link #ACTION_USB_PORT_CHANGED}
372      * containing the {@link UsbPortStatus} object for the port, or null if the port
373      * was removed.
374      *
375      * @hide
376      */
377     public static final String EXTRA_PORT_STATUS = "portStatus";
378 
379     /**
380      * Name of extra for {@link #ACTION_USB_DEVICE_ATTACHED} and
381      * {@link #ACTION_USB_DEVICE_DETACHED} broadcasts
382      * containing the {@link UsbDevice} object for the device.
383      */
384     public static final String EXTRA_DEVICE = "device";
385 
386     /**
387      * Name of extra for {@link #ACTION_USB_ACCESSORY_ATTACHED} and
388      * {@link #ACTION_USB_ACCESSORY_DETACHED} broadcasts
389      * containing the {@link UsbAccessory} object for the accessory.
390      */
391     public static final String EXTRA_ACCESSORY = "accessory";
392 
393     /**
394      * A long extra indicating ms from boot to get get_protocol UEvent
395      * This is obtained with SystemClock.elapsedRealtime()
396      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts.
397      *
398      * @hide
399      */
400     @SystemApi
401     public static final String EXTRA_ACCESSORY_UEVENT_TIME =
402             "android.hardware.usb.extra.ACCESSORY_UEVENT_TIME";
403 
404     /**
405      * An integer extra indicating numbers of send string during handshake
406      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts
407      *
408      * <p>For more information about control request with identifying string information
409      * between communicating with USB accessory handshake, refer to
410      * <a href="https://source.android.com/devices/accessories/aoa">AOA</a> developer guide.</p>
411      *
412      * @hide
413      */
414     @SystemApi
415     public static final String EXTRA_ACCESSORY_STRING_COUNT =
416             "android.hardware.usb.extra.ACCESSORY_STRING_COUNT";
417 
418     /**
419      * Boolean extra indicating whether got start accessory or not
420      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts.
421      *
422      * @hide
423      */
424     @SystemApi
425     public static final String EXTRA_ACCESSORY_START =
426             "android.hardware.usb.extra.ACCESSORY_START";
427 
428     /**
429 
430      * A long extra indicating the timestamp just before
431      * sending {@link #ACTION_USB_ACCESSORY_HANDSHAKE}.
432      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts.
433      *
434      * @hide
435      */
436     @SystemApi
437     public static final String EXTRA_ACCESSORY_HANDSHAKE_END =
438             "android.hardware.usb.extra.ACCESSORY_HANDSHAKE_END";
439 
440     /**
441      * Name of extra added to the {@link android.app.PendingIntent}
442      * passed into {@link #requestPermission(UsbDevice, PendingIntent)}
443      * or {@link #requestPermission(UsbAccessory, PendingIntent)}
444      * containing a boolean value indicating whether the user granted permission or not.
445      */
446     public static final String EXTRA_PERMISSION_GRANTED = "permission";
447 
448     /**
449      * Name of extra added to start systemui.usb.UsbPermissionActivity
450      * containing package name of the app which requests USB permission.
451      *
452      * @hide
453      */
454     public static final String EXTRA_PACKAGE = "android.hardware.usb.extra.PACKAGE";
455 
456     /**
457      * Name of extra added to start systemui.usb.UsbPermissionActivity
458      * containing the whether the app which requests USB permission can be set as default handler
459      * for USB device attach event or USB accessory attach event or not.
460      *
461      * @hide
462      */
463     public static final String EXTRA_CAN_BE_DEFAULT = "android.hardware.usb.extra.CAN_BE_DEFAULT";
464 
465     /**
466      * The Value for USB gadget hal is not presented.
467      *
468      * @hide
469      */
470     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
471     public static final int GADGET_HAL_NOT_SUPPORTED = -1;
472 
473     /**
474      * Value for Gadget Hal Version v1.0.
475      *
476      * @hide
477      */
478     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
479     public static final int GADGET_HAL_V1_0 = 10;
480 
481     /**
482      * Value for Gadget Hal Version v1.1.
483      *
484      * @hide
485      */
486     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
487     public static final int GADGET_HAL_V1_1 = 11;
488 
489     /**
490      * Value for Gadget Hal Version v1.2.
491      *
492      * @hide
493      */
494     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
495     public static final int GADGET_HAL_V1_2 = 12;
496 
497     /**
498      * Value for Gadget Hal Version v2.0.
499      *
500      * @hide
501      */
502     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
503     public static final int GADGET_HAL_V2_0 = 20;
504 
505     /**
506      * Value for USB_STATE is not configured.
507      *
508      * @hide
509      */
510     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
511     public static final int USB_DATA_TRANSFER_RATE_UNKNOWN = -1;
512 
513     /**
514      * Value for USB Transfer Rate of Low Speed in Mbps (real value is 1.5Mbps).
515      *
516      * @hide
517      */
518     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
519     public static final int USB_DATA_TRANSFER_RATE_LOW_SPEED = 2;
520 
521     /**
522      * Value for USB Transfer Rate of Full Speed in Mbps.
523      *
524      * @hide
525      */
526     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
527     public static final int USB_DATA_TRANSFER_RATE_FULL_SPEED = 12;
528 
529     /**
530      * Value for USB Transfer Rate of High Speed in Mbps.
531      *
532      * @hide
533      */
534     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
535     public static final int USB_DATA_TRANSFER_RATE_HIGH_SPEED = 480;
536 
537     /**
538      * Value for USB Transfer Rate of Super Speed in Mbps.
539      *
540      * @hide
541      */
542     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
543     public static final int USB_DATA_TRANSFER_RATE_5G = 5 * 1024;
544 
545     /**
546      * Value for USB Transfer Rate of 10G.
547      *
548      * @hide
549      */
550     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
551     public static final int USB_DATA_TRANSFER_RATE_10G = 10 * 1024;
552 
553     /**
554      * Value for USB Transfer Rate of 20G.
555      *
556      * @hide
557      */
558     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
559     public static final int USB_DATA_TRANSFER_RATE_20G = 20 * 1024;
560 
561     /**
562      * Value for USB Transfer Rate of 40G.
563      *
564      * @hide
565      */
566     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
567     public static final int USB_DATA_TRANSFER_RATE_40G = 40 * 1024;
568 
569     /**
570      * Returned when the client has to retry querying the version.
571      *
572      * @hide
573      */
574     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
575     public static final int USB_HAL_RETRY = -2;
576 
577     /**
578      * The Value for USB hal is not presented.
579      *
580      * @hide
581      */
582     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
583     public static final int USB_HAL_NOT_SUPPORTED = -1;
584 
585     /**
586      * Value for USB Hal Version v1.0.
587      *
588      * @hide
589      */
590     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
591     public static final int USB_HAL_V1_0 = 10;
592 
593     /**
594      * Value for USB Hal Version v1.1.
595      *
596      * @hide
597      */
598     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
599     public static final int USB_HAL_V1_1 = 11;
600 
601     /**
602      * Value for USB Hal Version v1.2.
603      *
604      * @hide
605      */
606     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
607     public static final int USB_HAL_V1_2 = 12;
608 
609     /**
610      * Value for USB Hal Version v1.3.
611      *
612      * @hide
613      */
614     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
615     public static final int USB_HAL_V1_3 = 13;
616 
617     /**
618      * Value for USB Hal Version v2.0.
619      *
620      * @hide
621      */
622     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
623     public static final int USB_HAL_V2_0 = 20;
624 
625     /**
626      * Code for the charging usb function. Passed into {@link #setCurrentFunctions(long)}
627      * Must be equal to {@link GadgetFunction#NONE}
628      * @hide
629      */
630     @SystemApi
631     public static final long FUNCTION_NONE = 0;
632 
633     /**
634      * Code for the mtp usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
635      * Must be equal to {@link GadgetFunction#MTP}
636      * @hide
637      */
638     @SystemApi
639     public static final long FUNCTION_MTP = 1 << 2;
640 
641     /**
642      * Code for the ptp usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
643      * Must be equal to {@link GadgetFunction#PTP}
644      * @hide
645      */
646     @SystemApi
647     public static final long FUNCTION_PTP = 1 << 4;
648 
649     /**
650      * Code for the rndis usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
651      * Must be equal to {@link GadgetFunction#RNDIS}
652      * @hide
653      */
654     @SystemApi
655     public static final long FUNCTION_RNDIS = 1 << 5;
656 
657     /**
658      * Code for the midi usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
659      * Must be equal to {@link GadgetFunction#MIDI}
660      * @hide
661      */
662     @SystemApi
663     public static final long FUNCTION_MIDI = 1 << 3;
664 
665     /**
666      * Code for the accessory usb function.
667      * Must be equal to {@link GadgetFunction#ACCESSORY}
668      * @hide
669      */
670     @SystemApi
671     public static final long FUNCTION_ACCESSORY = 1 << 1;
672 
673     /**
674      * Code for the audio source usb function.
675      * Must be equal to {@link GadgetFunction#AUDIO_SOURCE}
676      * @hide
677      */
678     @SystemApi
679     public static final long FUNCTION_AUDIO_SOURCE = 1 << 6;
680 
681     /**
682      * Code for the adb usb function.
683      * Must be equal to {@link GadgetFunction#ADB}
684      * @hide
685      */
686     @SystemApi
687     public static final long FUNCTION_ADB = 1;
688 
689     /**
690      * Code for the ncm source usb function.
691      * Must be equal to {@link GadgetFunction#NCM}
692      * @hide
693      */
694     @SystemApi
695     public static final long FUNCTION_NCM = 1 << 10;
696 
697     /**
698      * Code for the uvc usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
699      * Only supported if {@link #isUvcSupportEnabled()} returns true.
700      * Must be equal to {@link GadgetFunction#UVC}
701      * @hide
702      */
703     @SystemApi
704     public static final long FUNCTION_UVC = 1 << 7;
705 
706     private static final long SETTABLE_FUNCTIONS = FUNCTION_MTP | FUNCTION_PTP | FUNCTION_RNDIS
707             | FUNCTION_MIDI | FUNCTION_NCM | FUNCTION_UVC;
708 
709     private static final Map<String, Long> FUNCTION_NAME_TO_CODE = new HashMap<>();
710 
711     /**
712      * Counter for tracking UsbOperation operations.
713      */
714     private static final AtomicInteger sUsbOperationCount = new AtomicInteger();
715 
716     static {
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MTP, FUNCTION_MTP)717         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MTP, FUNCTION_MTP);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_PTP, FUNCTION_PTP)718         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_PTP, FUNCTION_PTP);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_RNDIS, FUNCTION_RNDIS)719         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_RNDIS, FUNCTION_RNDIS);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MIDI, FUNCTION_MIDI)720         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MIDI, FUNCTION_MIDI);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ACCESSORY, FUNCTION_ACCESSORY)721         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ACCESSORY, FUNCTION_ACCESSORY);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_AUDIO_SOURCE, FUNCTION_AUDIO_SOURCE)722         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_AUDIO_SOURCE, FUNCTION_AUDIO_SOURCE);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ADB, FUNCTION_ADB)723         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ADB, FUNCTION_ADB);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_NCM, FUNCTION_NCM)724         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_NCM, FUNCTION_NCM);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_UVC, FUNCTION_UVC)725         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_UVC, FUNCTION_UVC);
726     }
727 
728     /** @hide */
729     @LongDef(flag = true, prefix = { "FUNCTION_" }, value = {
730             FUNCTION_NONE,
731             FUNCTION_MTP,
732             FUNCTION_PTP,
733             FUNCTION_RNDIS,
734             FUNCTION_MIDI,
735             FUNCTION_ACCESSORY,
736             FUNCTION_AUDIO_SOURCE,
737             FUNCTION_ADB,
738             FUNCTION_NCM,
739             FUNCTION_UVC,
740     })
741     public @interface UsbFunctionMode {}
742 
743     /** @hide */
744     @IntDef(prefix = { "GADGET_HAL_" }, value = {
745             GADGET_HAL_NOT_SUPPORTED,
746             GADGET_HAL_V1_0,
747             GADGET_HAL_V1_1,
748             GADGET_HAL_V1_2,
749             GADGET_HAL_V2_0,
750     })
751     public @interface UsbGadgetHalVersion {}
752 
753     /** @hide */
754     @IntDef(prefix = { "USB_HAL_" }, value = {
755             USB_HAL_NOT_SUPPORTED,
756             USB_HAL_V1_0,
757             USB_HAL_V1_1,
758             USB_HAL_V1_2,
759             USB_HAL_V1_3,
760             USB_HAL_V2_0,
761     })
762     public @interface UsbHalVersion {}
763 
764     /**
765      * Listener to register for when the {@link DisplayPortAltModeInfo} changes on a
766      * {@link UsbPort}.
767      *
768      * @hide
769      */
770     @SystemApi
771     public interface DisplayPortAltModeInfoListener {
772         /**
773          * Callback to be executed when the {@link DisplayPortAltModeInfo} changes on a
774          * {@link UsbPort}.
775          *
776          * @param portId    String describing the {@link UsbPort} that was changed.
777          * @param info      New {@link DisplayPortAltModeInfo} for the corresponding portId.
778          */
onDisplayPortAltModeInfoChanged(@onNull String portId, @NonNull DisplayPortAltModeInfo info)779         public void onDisplayPortAltModeInfoChanged(@NonNull String portId,
780                 @NonNull DisplayPortAltModeInfo info);
781     }
782 
783     /**
784      * Holds callback and executor data to be passed across UsbService.
785      */
786     private class DisplayPortAltModeInfoDispatchingListener extends
787             IDisplayPortAltModeInfoListener.Stub {
788 
onDisplayPortAltModeInfoChanged(String portId, DisplayPortAltModeInfo displayPortAltModeInfo)789         public void onDisplayPortAltModeInfoChanged(String portId,
790                 DisplayPortAltModeInfo displayPortAltModeInfo) {
791             synchronized (mDisplayPortListenersLock) {
792                 for (Map.Entry<DisplayPortAltModeInfoListener, Executor> entry :
793                         mDisplayPortListeners.entrySet()) {
794                     Executor executor = entry.getValue();
795                     DisplayPortAltModeInfoListener callback = entry.getKey();
796                     final long token = Binder.clearCallingIdentity();
797                     try {
798                         executor.execute(() -> callback.onDisplayPortAltModeInfoChanged(portId,
799                                 displayPortAltModeInfo));
800                     } catch (Exception e) {
801                         Slog.e(TAG, "Exception during onDisplayPortAltModeInfoChanged from "
802                                 + "executor: " + executor, e);
803                     } finally {
804                         Binder.restoreCallingIdentity(token);
805                     }
806                 }
807             }
808         }
809     }
810 
811     private final Context mContext;
812     private final IUsbManager mService;
813     private final Object mDisplayPortListenersLock = new Object();
814     @GuardedBy("mDisplayPortListenersLock")
815     private ArrayMap<DisplayPortAltModeInfoListener, Executor> mDisplayPortListeners;
816     @GuardedBy("mDisplayPortListenersLock")
817     private DisplayPortAltModeInfoDispatchingListener mDisplayPortServiceListener;
818 
819     /**
820      * @hide
821      */
822     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
UsbManager(Context context, IUsbManager service)823     public UsbManager(Context context, IUsbManager service) {
824         mContext = context;
825         mService = service;
826     }
827 
828     /**
829      * Returns a HashMap containing all USB devices currently attached.
830      * USB device name is the key for the returned HashMap.
831      * The result will be empty if no devices are attached, or if
832      * USB host mode is inactive or unsupported.
833      *
834      * @return HashMap containing all connected USB devices.
835      */
836     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
getDeviceList()837     public HashMap<String,UsbDevice> getDeviceList() {
838         HashMap<String,UsbDevice> result = new HashMap<String,UsbDevice>();
839         if (mService == null) {
840             return result;
841         }
842         Bundle bundle = new Bundle();
843         try {
844             mService.getDeviceList(bundle);
845             for (String name : bundle.keySet()) {
846                 result.put(name, (UsbDevice)bundle.get(name));
847             }
848             return result;
849         } catch (RemoteException e) {
850             throw e.rethrowFromSystemServer();
851         }
852     }
853 
854     /**
855      * Opens the device so it can be used to send and receive
856      * data using {@link android.hardware.usb.UsbRequest}.
857      *
858      * @param device the device to open
859      * @return a {@link UsbDeviceConnection}, or {@code null} if open failed
860      */
861     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
openDevice(UsbDevice device)862     public UsbDeviceConnection openDevice(UsbDevice device) {
863         try {
864             String deviceName = device.getDeviceName();
865             ParcelFileDescriptor pfd = mService.openDevice(deviceName, mContext.getPackageName());
866             if (pfd != null) {
867                 UsbDeviceConnection connection = new UsbDeviceConnection(device);
868                 boolean result = connection.open(deviceName, pfd, mContext);
869                 pfd.close();
870                 if (result) {
871                     return connection;
872                 }
873             }
874         } catch (Exception e) {
875             Log.e(TAG, "exception in UsbManager.openDevice", e);
876         }
877         return null;
878     }
879 
880     /**
881      * Returns a list of currently attached USB accessories.
882      * (in the current implementation there can be at most one)
883      *
884      * @return list of USB accessories, or null if none are attached.
885      */
886     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
getAccessoryList()887     public UsbAccessory[] getAccessoryList() {
888         if (mService == null) {
889             return null;
890         }
891         try {
892             UsbAccessory accessory = mService.getCurrentAccessory();
893             if (accessory == null) {
894                 return null;
895             } else {
896                 return new UsbAccessory[] { accessory };
897             }
898         } catch (RemoteException e) {
899             throw e.rethrowFromSystemServer();
900         }
901     }
902 
903     /**
904      * Opens a file descriptor for reading and writing data to the USB accessory.
905      *
906      * <p>If data is read from the {@link java.io.InputStream} created from this file descriptor all
907      * data of a USB transfer should be read at once. If only a partial request is read the rest of
908      * the transfer is dropped.
909      *
910      * @param accessory the USB accessory to open
911      * @return file descriptor, or null if the accessory could not be opened.
912      */
913     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
openAccessory(UsbAccessory accessory)914     public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
915         try {
916             return mService.openAccessory(accessory);
917         } catch (RemoteException e) {
918             throw e.rethrowFromSystemServer();
919         }
920     }
921 
922     /**
923      * Gets the functionfs control file descriptor for the given function, with
924      * the usb descriptors and strings already written. The file descriptor is used
925      * by the function implementation to handle events and control requests.
926      *
927      * @param function to get control fd for. Currently {@link #FUNCTION_MTP} and
928      * {@link #FUNCTION_PTP} are supported.
929      * @return A ParcelFileDescriptor holding the valid fd, or null if the fd was not found.
930      *
931      * @hide
932      */
getControlFd(long function)933     public ParcelFileDescriptor getControlFd(long function) {
934         try {
935             return mService.getControlFd(function);
936         } catch (RemoteException e) {
937             throw e.rethrowFromSystemServer();
938         }
939     }
940 
941     /**
942      * Returns true if the caller has permission to access the device.
943      * Permission might have been granted temporarily via
944      * {@link #requestPermission(UsbDevice, PendingIntent)} or
945      * by the user choosing the caller as the default application for the device.
946      * Permission for USB devices of class {@link UsbConstants#USB_CLASS_VIDEO} for clients that
947      * target SDK {@link android.os.Build.VERSION_CODES#P} and above can be granted only if they
948      * have additionally the {@link android.Manifest.permission#CAMERA} permission.
949      *
950      * @param device to check permissions for
951      * @return true if caller has permission
952      */
953     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
hasPermission(UsbDevice device)954     public boolean hasPermission(UsbDevice device) {
955         if (mService == null) {
956             return false;
957         }
958         try {
959             return mService.hasDevicePermission(device, mContext.getPackageName());
960         } catch (RemoteException e) {
961             throw e.rethrowFromSystemServer();
962         }
963     }
964 
965     /**
966      * Returns true if the caller has permission to access the device. It's similar to the
967      * {@link #hasPermission(UsbDevice)} but allows to specify a different package/uid/pid.
968      *
969      * <p>Not for third-party apps.</p>
970      *
971      * @hide
972      */
973     @RequiresPermission(Manifest.permission.MANAGE_USB)
974     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
hasPermission(@onNull UsbDevice device, @NonNull String packageName, int pid, int uid)975     public boolean hasPermission(@NonNull UsbDevice device, @NonNull String packageName,
976             int pid, int uid) {
977         if (mService == null) {
978             return false;
979         }
980         try {
981             return mService.hasDevicePermissionWithIdentity(device, packageName, pid, uid);
982         } catch (RemoteException e) {
983             throw e.rethrowFromSystemServer();
984         }
985     }
986 
987     /**
988      * Returns true if the caller has permission to access the accessory.
989      * Permission might have been granted temporarily via
990      * {@link #requestPermission(UsbAccessory, PendingIntent)} or
991      * by the user choosing the caller as the default application for the accessory.
992      *
993      * @param accessory to check permissions for
994      * @return true if caller has permission
995      */
996     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
hasPermission(UsbAccessory accessory)997     public boolean hasPermission(UsbAccessory accessory) {
998         if (mService == null) {
999             return false;
1000         }
1001         try {
1002             return mService.hasAccessoryPermission(accessory);
1003         } catch (RemoteException e) {
1004             throw e.rethrowFromSystemServer();
1005         }
1006     }
1007 
1008     /**
1009      * Returns true if the caller has permission to access the accessory. It's similar to the
1010      * {@link #hasPermission(UsbAccessory)} but allows to specify a different uid/pid.
1011      *
1012      * <p>Not for third-party apps.</p>
1013      *
1014      * @hide
1015      */
1016     @RequiresPermission(Manifest.permission.MANAGE_USB)
1017     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
hasPermission(@onNull UsbAccessory accessory, int pid, int uid)1018     public boolean hasPermission(@NonNull UsbAccessory accessory, int pid, int uid) {
1019         if (mService == null) {
1020             return false;
1021         }
1022         try {
1023             return mService.hasAccessoryPermissionWithIdentity(accessory, pid, uid);
1024         } catch (RemoteException e) {
1025             throw e.rethrowFromSystemServer();
1026         }
1027     }
1028 
1029     /**
1030      * Requests temporary permission for the given package to access the device.
1031      * This may result in a system dialog being displayed to the user
1032      * if permission had not already been granted.
1033      * Success or failure is returned via the {@link android.app.PendingIntent} pi.
1034      * If successful, this grants the caller permission to access the device only
1035      * until the device is disconnected.
1036      *
1037      * The following extras will be added to pi:
1038      * <ul>
1039      * <li> {@link #EXTRA_DEVICE} containing the device passed into this call
1040      * <li> {@link #EXTRA_PERMISSION_GRANTED} containing boolean indicating whether
1041      * permission was granted by the user
1042      * </ul>
1043      *
1044      * Permission for USB devices of class {@link UsbConstants#USB_CLASS_VIDEO} for clients that
1045      * target SDK {@link android.os.Build.VERSION_CODES#P} and above can be granted only if they
1046      * have additionally the {@link android.Manifest.permission#CAMERA} permission.
1047      *
1048      * @param device to request permissions for
1049      * @param pi PendingIntent for returning result
1050      */
1051     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
requestPermission(UsbDevice device, PendingIntent pi)1052     public void requestPermission(UsbDevice device, PendingIntent pi) {
1053         try {
1054             mService.requestDevicePermission(device, mContext.getPackageName(), pi);
1055         } catch (RemoteException e) {
1056             throw e.rethrowFromSystemServer();
1057         }
1058     }
1059 
1060     /**
1061      * Requests temporary permission for the given package to access the accessory.
1062      * This may result in a system dialog being displayed to the user
1063      * if permission had not already been granted.
1064      * Success or failure is returned via the {@link android.app.PendingIntent} pi.
1065      * If successful, this grants the caller permission to access the accessory only
1066      * until the device is disconnected.
1067      *
1068      * The following extras will be added to pi:
1069      * <ul>
1070      * <li> {@link #EXTRA_ACCESSORY} containing the accessory passed into this call
1071      * <li> {@link #EXTRA_PERMISSION_GRANTED} containing boolean indicating whether
1072      * permission was granted by the user
1073      * </ul>
1074      *
1075      * @param accessory to request permissions for
1076      * @param pi PendingIntent for returning result
1077      */
1078     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
requestPermission(UsbAccessory accessory, PendingIntent pi)1079     public void requestPermission(UsbAccessory accessory, PendingIntent pi) {
1080         try {
1081             mService.requestAccessoryPermission(accessory, mContext.getPackageName(), pi);
1082         } catch (RemoteException e) {
1083             throw e.rethrowFromSystemServer();
1084         }
1085     }
1086 
1087     /**
1088      * Grants permission for USB device without showing system dialog.
1089      * Only system components can call this function.
1090      * @param device to request permissions for
1091      *
1092      * @hide
1093      */
grantPermission(UsbDevice device)1094     public void grantPermission(UsbDevice device) {
1095         grantPermission(device, Process.myUid());
1096     }
1097 
1098     /**
1099      * Grants permission for USB device to given uid without showing system dialog.
1100      * Only system components can call this function.
1101      * @param device to request permissions for
1102      * @uid uid to give permission
1103      *
1104      * @hide
1105      */
grantPermission(UsbDevice device, int uid)1106     public void grantPermission(UsbDevice device, int uid) {
1107         try {
1108             mService.grantDevicePermission(device, uid);
1109         } catch (RemoteException e) {
1110             throw e.rethrowFromSystemServer();
1111         }
1112     }
1113 
1114     /**
1115      * Grants permission to specified package for USB device without showing system dialog.
1116      * Only system components can call this function, as it requires the MANAGE_USB permission.
1117      * @param device to request permissions for
1118      * @param packageName of package to grant permissions
1119      *
1120      * @hide
1121      */
1122     @SystemApi
1123     @RequiresPermission(Manifest.permission.MANAGE_USB)
grantPermission(UsbDevice device, String packageName)1124     public void grantPermission(UsbDevice device, String packageName) {
1125         try {
1126             int uid = mContext.getPackageManager()
1127                 .getPackageUidAsUser(packageName, mContext.getUserId());
1128             grantPermission(device, uid);
1129         } catch (NameNotFoundException e) {
1130             Log.e(TAG, "Package " + packageName + " not found.", e);
1131         }
1132     }
1133 
1134     /**
1135      * Returns true if the specified USB function is currently enabled when in device mode.
1136      * <p>
1137      * USB functions represent interfaces which are published to the host to access
1138      * services offered by the device.
1139      * </p>
1140      *
1141      * @deprecated use getCurrentFunctions() instead.
1142      * @param function name of the USB function
1143      * @return true if the USB function is enabled
1144      *
1145      * @hide
1146      */
1147     @Deprecated
1148     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
isFunctionEnabled(String function)1149     public boolean isFunctionEnabled(String function) {
1150         try {
1151             return mService.isFunctionEnabled(function);
1152         } catch (RemoteException e) {
1153             throw e.rethrowFromSystemServer();
1154         }
1155     }
1156 
1157     /**
1158      * Sets the current USB functions when in device mode.
1159      * <p>
1160      * USB functions represent interfaces which are published to the host to access
1161      * services offered by the device.
1162      * </p><p>
1163      * This method is intended to select among primary USB functions.  The system may
1164      * automatically activate additional functions such as {@link #USB_FUNCTION_ADB}
1165      * or {@link #USB_FUNCTION_ACCESSORY} based on other settings and states.
1166      * </p><p>
1167      * An argument of 0 indicates that the device is charging, and can pick any
1168      * appropriate function for that purpose.
1169      * </p><p>
1170      * Note: This function is asynchronous and may fail silently without applying
1171      * the requested changes.
1172      * </p>
1173      *
1174      * @param functions the USB function(s) to set, as a bitwise mask.
1175      *                  Must satisfy {@link UsbManager#areSettableFunctions}
1176      *
1177      * @hide
1178      */
1179     @SystemApi
1180     @RequiresPermission(Manifest.permission.MANAGE_USB)
setCurrentFunctions(@sbFunctionMode long functions)1181     public void setCurrentFunctions(@UsbFunctionMode long functions) {
1182         int operationId = sUsbOperationCount.incrementAndGet() + Binder.getCallingUid();
1183         try {
1184             mService.setCurrentFunctions(functions, operationId);
1185         } catch (RemoteException e) {
1186             Log.e(TAG, "setCurrentFunctions: failed to call setCurrentFunctions. functions:"
1187                         + functions + ", opId:" + operationId, e);
1188             throw e.rethrowFromSystemServer();
1189         }
1190     }
1191 
1192     /**
1193      * Sets the current USB functions when in device mode.
1194      *
1195      * @deprecated use setCurrentFunctions(long) instead.
1196      * @param functions the USB function(s) to set.
1197      * @param usbDataUnlocked unused
1198 
1199      * @hide
1200      */
1201     @Deprecated
1202     @UnsupportedAppUsage
setCurrentFunction(String functions, boolean usbDataUnlocked)1203     public void setCurrentFunction(String functions, boolean usbDataUnlocked) {
1204         int operationId = sUsbOperationCount.incrementAndGet() + Binder.getCallingUid();
1205         try {
1206             mService.setCurrentFunction(functions, usbDataUnlocked, operationId);
1207         } catch (RemoteException e) {
1208             Log.e(TAG, "setCurrentFunction: failed to call setCurrentFunction. functions:"
1209                         + functions + ", opId:" + operationId, e);
1210             throw e.rethrowFromSystemServer();
1211         }
1212     }
1213 
1214     /**
1215      * Returns the current USB functions in device mode.
1216      * <p>
1217      * This function returns the state of primary USB functions and can return a
1218      * mask containing any usb function(s) except for ADB.
1219      * </p>
1220      *
1221      * @return The currently enabled functions, in a bitwise mask.
1222      * A zero mask indicates that the current function is the charging function.
1223      *
1224      * @hide
1225      */
1226     @SystemApi
1227     @RequiresPermission(Manifest.permission.MANAGE_USB)
getCurrentFunctions()1228     public long getCurrentFunctions() {
1229         try {
1230             return mService.getCurrentFunctions();
1231         } catch (RemoteException e) {
1232             throw e.rethrowFromSystemServer();
1233         }
1234     }
1235 
1236     /**
1237      * Sets the screen unlocked functions, which are persisted and set as the current functions
1238      * whenever the screen is unlocked.
1239      * <p>
1240      * A zero mask has the effect of switching off this feature, so functions
1241      * no longer change on screen unlock.
1242      * </p><p>
1243      * Note: When the screen is on, this method will apply given functions as current functions,
1244      * which is asynchronous and may fail silently without applying the requested changes.
1245      * </p>
1246      *
1247      * @param functions functions to set, in a bitwise mask.
1248      *                  Must satisfy {@link UsbManager#areSettableFunctions}
1249      *
1250      * @hide
1251      */
setScreenUnlockedFunctions(long functions)1252     public void setScreenUnlockedFunctions(long functions) {
1253         try {
1254             mService.setScreenUnlockedFunctions(functions);
1255         } catch (RemoteException e) {
1256             throw e.rethrowFromSystemServer();
1257         }
1258     }
1259 
1260     /**
1261      * Gets the current screen unlocked functions.
1262      *
1263      * @return The currently set screen enabled functions.
1264      * A zero mask indicates that the screen unlocked functions feature is not enabled.
1265      *
1266      * @hide
1267      */
getScreenUnlockedFunctions()1268     public long getScreenUnlockedFunctions() {
1269         try {
1270             return mService.getScreenUnlockedFunctions();
1271         } catch (RemoteException e) {
1272             throw e.rethrowFromSystemServer();
1273         }
1274     }
1275 
1276     /**
1277      * Get the Current USB Bandwidth.
1278      * <p>
1279      * This function returns the current USB bandwidth through USB Gadget HAL.
1280      * It should be used when Android device is in USB peripheral mode and
1281      * connects to a USB host. If USB state is not configued, API will return
1282      * {@value #USB_DATA_TRANSFER_RATE_UNKNOWN}. In addition, the unit of the
1283      * return value is Mbps.
1284      * </p>
1285      *
1286      * @return The value of currently USB Bandwidth.
1287      *
1288      * @hide
1289      */
1290     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1291     @RequiresPermission(Manifest.permission.MANAGE_USB)
getUsbBandwidthMbps()1292     public int getUsbBandwidthMbps() {
1293         int usbSpeed;
1294         try {
1295             usbSpeed = mService.getCurrentUsbSpeed();
1296         } catch (RemoteException e) {
1297             throw e.rethrowFromSystemServer();
1298         }
1299         return usbSpeedToBandwidth(usbSpeed);
1300     }
1301 
1302     /**
1303      * Get the Current Gadget Hal Version.
1304      * <p>
1305      * This function returns the current Gadget Hal Version.
1306      * </p>
1307      *
1308      * @return a integer {@code GADGET_HAL_*} represent hal version.
1309      *
1310      * @hide
1311      */
1312     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1313     @RequiresPermission(Manifest.permission.MANAGE_USB)
getGadgetHalVersion()1314     public @UsbGadgetHalVersion int getGadgetHalVersion() {
1315         try {
1316             return mService.getGadgetHalVersion();
1317         } catch (RemoteException e) {
1318             throw e.rethrowFromSystemServer();
1319         }
1320     }
1321 
1322     /**
1323      * Get the Current USB Hal Version.
1324      * <p>
1325      * This function returns the current USB Hal Version.
1326      * </p>
1327      *
1328      * @return a integer {@code USB_HAL_*} represent hal version.
1329      *
1330      * @hide
1331      */
1332     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1333     @RequiresPermission(Manifest.permission.MANAGE_USB)
getUsbHalVersion()1334     public @UsbHalVersion int getUsbHalVersion() {
1335         try {
1336             return mService.getUsbHalVersion();
1337         } catch (RemoteException e) {
1338             throw e.rethrowFromSystemServer();
1339         }
1340     }
1341 
1342     /**
1343      * Resets the USB Gadget.
1344      * <p>
1345      * Performs USB data stack reset through USB Gadget HAL.
1346      * It will force USB data connection reset. The connection will disconnect and reconnect.
1347      * </p>
1348      *
1349      * @hide
1350      */
1351     @SystemApi
1352     @RequiresPermission(Manifest.permission.MANAGE_USB)
resetUsbGadget()1353     public void resetUsbGadget() {
1354         try {
1355             mService.resetUsbGadget();
1356         } catch (RemoteException e) {
1357             throw e.rethrowFromSystemServer();
1358         }
1359     }
1360 
1361     /**
1362      * Returns whether UVC is advertised to be supported or not. SELinux
1363      * enforces that this function returns {@code false} when called from a
1364      * process that doesn't belong either to a system app, or the
1365      * DeviceAsWebcam Service.
1366      *
1367      * @return true if UVC is supported, false if UVC is not supported or if
1368      *         called from a non-system app that isn't DeviceAsWebcam Service.
1369      * @hide
1370      */
1371     @SystemApi
isUvcSupportEnabled()1372     public static boolean isUvcSupportEnabled() {
1373         return SystemProperties.getBoolean("ro.usb.uvc.enabled", false);
1374     }
1375 
1376     /**
1377      * Enable/Disable the USB data signaling.
1378      * <p>
1379      * Enables/Disables USB data path of all USB ports.
1380      * It will force to stop or restore USB data signaling.
1381      * </p>
1382      *
1383      * @param enable enable or disable USB data signaling
1384      * @return true enable or disable USB data successfully
1385      *         false if something wrong
1386      *
1387      * @hide
1388      */
1389     @RequiresPermission(Manifest.permission.MANAGE_USB)
enableUsbDataSignal(boolean enable)1390     public boolean enableUsbDataSignal(boolean enable) {
1391         return setUsbDataSignal(getPorts(), !enable, /* revertOnFailure= */ true);
1392     }
1393 
setUsbDataSignal(List<UsbPort> usbPorts, boolean disable, boolean revertOnFailure)1394     private boolean setUsbDataSignal(List<UsbPort> usbPorts, boolean disable,
1395             boolean revertOnFailure) {
1396         List<UsbPort> changedPorts = new ArrayList<>();
1397         for (int i = 0; i < usbPorts.size(); i++) {
1398             UsbPort port = usbPorts.get(i);
1399             if (isPortDisabled(port) != disable) {
1400                 changedPorts.add(port);
1401                 if (port.enableUsbData(!disable) != UsbPort.ENABLE_USB_DATA_SUCCESS
1402                         && revertOnFailure) {
1403                     Log.e(TAG, "Failed to set usb data signal for portID(" + port.getId() + ")");
1404                     setUsbDataSignal(changedPorts, !disable, /* revertOnFailure= */ false);
1405                     return false;
1406                 }
1407             }
1408         }
1409         return true;
1410     }
1411 
isPortDisabled(UsbPort usbPort)1412     private boolean isPortDisabled(UsbPort usbPort) {
1413         return (getPortStatus(usbPort).getUsbDataStatus() & DATA_STATUS_DISABLED_FORCE)
1414                 == DATA_STATUS_DISABLED_FORCE;
1415     }
1416 
1417     /**
1418      * Returns a list of physical USB ports on the device.
1419      * <p>
1420      * This list is guaranteed to contain all dual-role USB Type C ports but it might
1421      * be missing other ports depending on whether the kernel USB drivers have been
1422      * updated to publish all of the device's ports through the new "dual_role_usb"
1423      * device class (which supports all types of ports despite its name).
1424      * </p>
1425      *
1426      * @return The list of USB ports
1427      *
1428      * @hide
1429      */
1430     @SystemApi
1431     @RequiresPermission(Manifest.permission.MANAGE_USB)
getPorts()1432     public @NonNull List<UsbPort> getPorts() {
1433         if (mService == null) {
1434             return Collections.emptyList();
1435         }
1436 
1437         List<ParcelableUsbPort> parcelablePorts;
1438         try {
1439             parcelablePorts = mService.getPorts();
1440         } catch (RemoteException e) {
1441             throw e.rethrowFromSystemServer();
1442         }
1443 
1444         if (parcelablePorts == null) {
1445             return Collections.emptyList();
1446         } else {
1447             int numPorts = parcelablePorts.size();
1448 
1449             ArrayList<UsbPort> ports = new ArrayList<>(numPorts);
1450             for (int i = 0; i < numPorts; i++) {
1451                 ports.add(parcelablePorts.get(i).getUsbPort(this));
1452             }
1453 
1454             return ports;
1455         }
1456     }
1457 
1458     /**
1459      * Should only be called by {@link UsbPort#getStatus}.
1460      *
1461      * @hide
1462      */
getPortStatus(UsbPort port)1463     UsbPortStatus getPortStatus(UsbPort port) {
1464         try {
1465             return mService.getPortStatus(port.getId());
1466         } catch (RemoteException e) {
1467             throw e.rethrowFromSystemServer();
1468         }
1469     }
1470 
1471     /**
1472      * Should only be called by {@link UsbPort#setRoles}.
1473      *
1474      * @hide
1475      */
setPortRoles(UsbPort port, int powerRole, int dataRole)1476     void setPortRoles(UsbPort port, int powerRole, int dataRole) {
1477         Log.d(TAG, "setPortRoles Package:" + mContext.getPackageName());
1478         try {
1479             mService.setPortRoles(port.getId(), powerRole, dataRole);
1480         } catch (RemoteException e) {
1481             throw e.rethrowFromSystemServer();
1482         }
1483     }
1484 
1485     /**
1486      * Enables USB port contaminant detection algorithm.
1487      *
1488      * @hide
1489      */
1490     @RequiresPermission(Manifest.permission.MANAGE_USB)
enableContaminantDetection(@onNull UsbPort port, boolean enable)1491     void enableContaminantDetection(@NonNull UsbPort port, boolean enable) {
1492         try {
1493             mService.enableContaminantDetection(port.getId(), enable);
1494         } catch (RemoteException e) {
1495             throw e.rethrowFromSystemServer();
1496         }
1497     }
1498 
1499     /**
1500      * Should only be called by {@link UsbPort#enableLimitPowerTransfer}.
1501      * <p>
1502      * limits or restores power transfer in and out of USB port.
1503      *
1504      * @param port USB port for which power transfer has to be limited or restored.
1505      * @param limit limit power transfer when true.
1506      *              relax power transfer restrictions when false.
1507      * @param operationId operationId for the request.
1508      * @param callback callback object to be invoked when the operation is complete.
1509      *
1510      * @hide
1511      */
1512     @RequiresPermission(Manifest.permission.MANAGE_USB)
enableLimitPowerTransfer(@onNull UsbPort port, boolean limit, int operationId, IUsbOperationInternal callback)1513     void enableLimitPowerTransfer(@NonNull UsbPort port, boolean limit, int operationId,
1514             IUsbOperationInternal callback) {
1515         Objects.requireNonNull(port, "enableLimitPowerTransfer:port must not be null. opId:"
1516                 + operationId);
1517         try {
1518             mService.enableLimitPowerTransfer(port.getId(), limit, operationId, callback);
1519         } catch (RemoteException e) {
1520             Log.e(TAG, "enableLimitPowerTransfer failed. opId:" + operationId, e);
1521             try {
1522                 callback.onOperationComplete(UsbOperationInternal.USB_OPERATION_ERROR_INTERNAL);
1523             } catch (RemoteException r) {
1524                 Log.e(TAG, "enableLimitPowerTransfer failed to call onOperationComplete. opId:"
1525                         + operationId, r);
1526             }
1527             throw e.rethrowFromSystemServer();
1528         }
1529     }
1530 
1531     /**
1532      * Should only be called by {@link UsbPort#resetUsbPort}.
1533      * <p>
1534      * Disable and then re-enable USB data signaling.
1535      *
1536      * Reset USB first port..
1537      * It will force to stop and restart USB data signaling.
1538      * Call UsbPort API if the device has more than one UsbPort.
1539      * </p>
1540      *
1541      * @param port reset the USB Port
1542      * @return true enable or disable USB data successfully
1543      *         false if something wrong
1544      *
1545      * Should only be called by {@link UsbPort#resetUsbPort}.
1546      *
1547      * @hide
1548      */
1549     @RequiresPermission(Manifest.permission.MANAGE_USB)
resetUsbPort(@onNull UsbPort port, int operationId, IUsbOperationInternal callback)1550     void resetUsbPort(@NonNull UsbPort port, int operationId,
1551             IUsbOperationInternal callback) {
1552         Objects.requireNonNull(port, "resetUsbPort: port must not be null. opId:" + operationId);
1553         try {
1554             mService.resetUsbPort(port.getId(), operationId, callback);
1555         } catch (RemoteException e) {
1556             Log.e(TAG, "resetUsbPort: failed. ", e);
1557             try {
1558                 callback.onOperationComplete(UsbOperationInternal.USB_OPERATION_ERROR_INTERNAL);
1559             } catch (RemoteException r) {
1560                 Log.e(TAG, "resetUsbPort: failed to call onOperationComplete. opId:"
1561                         + operationId, r);
1562             }
1563             throw e.rethrowFromSystemServer();
1564         }
1565     }
1566 
1567     /**
1568      * Should only be called by {@link UsbPort#enableUsbData}.
1569      * <p>
1570      * Enables or disables USB data on the specific port.
1571      *
1572      * @param port USB port for which USB data needs to be enabled or disabled.
1573      * @param enable Enable USB data when true.
1574      *               Disable USB data when false.
1575      * @param operationId operationId for the request.
1576      * @param callback callback object to be invoked when the operation is complete.
1577      * @return True when the operation is asynchronous. The caller must therefore call
1578      *         {@link UsbOperationInternal#waitForOperationComplete} for processing
1579      *         the result.
1580      *         False when the operation is synchronous. Caller can proceed reading the result
1581      *         through {@link UsbOperationInternal#getStatus}
1582      * @hide
1583      */
1584     @RequiresPermission(Manifest.permission.MANAGE_USB)
enableUsbData(@onNull UsbPort port, boolean enable, int operationId, IUsbOperationInternal callback)1585     boolean enableUsbData(@NonNull UsbPort port, boolean enable, int operationId,
1586             IUsbOperationInternal callback) {
1587         Objects.requireNonNull(port, "enableUsbData: port must not be null. opId:" + operationId);
1588         try {
1589             return mService.enableUsbData(port.getId(), enable, operationId, callback);
1590         } catch (RemoteException e) {
1591             Log.e(TAG, "enableUsbData: failed. opId:" + operationId, e);
1592             try {
1593                 callback.onOperationComplete(UsbOperationInternal.USB_OPERATION_ERROR_INTERNAL);
1594             } catch (RemoteException r) {
1595                 Log.e(TAG, "enableUsbData: failed to call onOperationComplete. opId:"
1596                         + operationId, r);
1597             }
1598             throw e.rethrowFromSystemServer();
1599         }
1600     }
1601 
1602     /**
1603      * Should only be called by {@link UsbPort#enableUsbDataWhileDocked}.
1604      * <p>
1605      * Enables or disables USB data when disabled due to docking event.
1606      *
1607      * @param port USB port for which USB data needs to be enabled.
1608      * @param operationId operationId for the request.
1609      * @param callback callback object to be invoked when the operation is complete.
1610      * @hide
1611      */
1612     @RequiresPermission(Manifest.permission.MANAGE_USB)
enableUsbDataWhileDocked(@onNull UsbPort port, int operationId, IUsbOperationInternal callback)1613     void enableUsbDataWhileDocked(@NonNull UsbPort port, int operationId,
1614             IUsbOperationInternal callback) {
1615         Objects.requireNonNull(port, "enableUsbDataWhileDocked: port must not be null. opId:"
1616                 + operationId);
1617         try {
1618             mService.enableUsbDataWhileDocked(port.getId(), operationId, callback);
1619         } catch (RemoteException e) {
1620             Log.e(TAG, "enableUsbDataWhileDocked: failed. opId:" + operationId, e);
1621             try {
1622                 callback.onOperationComplete(UsbOperationInternal.USB_OPERATION_ERROR_INTERNAL);
1623             } catch (RemoteException r) {
1624                 Log.e(TAG, "enableUsbDataWhileDocked: failed to call onOperationComplete. opId:"
1625                         + operationId, r);
1626             }
1627             throw e.rethrowFromSystemServer();
1628         }
1629     }
1630 
1631     @GuardedBy("mDisplayPortListenersLock")
1632     @RequiresPermission(Manifest.permission.MANAGE_USB)
registerDisplayPortAltModeEventsIfNeededLocked()1633     private boolean registerDisplayPortAltModeEventsIfNeededLocked() {
1634         DisplayPortAltModeInfoDispatchingListener displayPortDispatchingListener =
1635                 new DisplayPortAltModeInfoDispatchingListener();
1636         try {
1637             if (mService.registerForDisplayPortEvents(displayPortDispatchingListener)) {
1638                 mDisplayPortServiceListener = displayPortDispatchingListener;
1639                 return true;
1640             }
1641             return false;
1642         } catch (RemoteException e) {
1643             throw e.rethrowFromSystemServer();
1644         }
1645     }
1646 
1647     /**
1648      * Registers the given listener to listen for DisplayPort Alt Mode changes.
1649      * <p>
1650      * If this method returns without Exceptions, the caller should ensure to call
1651      * {@link #unregisterDisplayPortAltModeListener} when it no longer requires updates.
1652      *
1653      * @param executor          Executor on which to run the listener.
1654      * @param listener          DisplayPortAltModeInfoListener invoked on DisplayPortAltModeInfo
1655      *                          changes. See {@link #DisplayPortAltModeInfoListener} for listener
1656      *                          details.
1657      *
1658      * @throws IllegalStateException if listener has already been registered previously but not
1659      * unregistered or an unexpected system failure occurs.
1660      *
1661      * @hide
1662      */
1663     @SystemApi
1664     @RequiresPermission(Manifest.permission.MANAGE_USB)
registerDisplayPortAltModeInfoListener( @onNull @allbackExecutor Executor executor, @NonNull DisplayPortAltModeInfoListener listener)1665     public void registerDisplayPortAltModeInfoListener(
1666             @NonNull @CallbackExecutor Executor executor,
1667             @NonNull DisplayPortAltModeInfoListener listener) {
1668         Objects.requireNonNull(executor, "registerDisplayPortAltModeInfoListener: "
1669                 + "executor must not be null.");
1670         Objects.requireNonNull(listener, "registerDisplayPortAltModeInfoListener: "
1671                 + "listener must not be null.");
1672 
1673         synchronized (mDisplayPortListenersLock) {
1674             if (mDisplayPortListeners == null) {
1675                 mDisplayPortListeners = new ArrayMap<DisplayPortAltModeInfoListener,
1676                         Executor>();
1677             }
1678 
1679             if (mDisplayPortServiceListener == null) {
1680                 if (!registerDisplayPortAltModeEventsIfNeededLocked()) {
1681                     throw new IllegalStateException("Unexpected failure registering service "
1682                             + "listener");
1683                 }
1684             }
1685             if (mDisplayPortListeners.containsKey(listener)) {
1686                 throw new IllegalStateException("Listener has already been registered.");
1687             }
1688 
1689             mDisplayPortListeners.put(listener, executor);
1690         }
1691     }
1692 
1693     @GuardedBy("mDisplayPortListenersLock")
1694     @RequiresPermission(Manifest.permission.MANAGE_USB)
unregisterDisplayPortAltModeEventsLocked()1695     private void unregisterDisplayPortAltModeEventsLocked() {
1696         if (mDisplayPortServiceListener != null) {
1697             try {
1698                 mService.unregisterForDisplayPortEvents(mDisplayPortServiceListener);
1699             } catch (RemoteException e) {
1700                 throw e.rethrowFromSystemServer();
1701             } finally {
1702                 // If there was a RemoteException, the system server may have died,
1703                 // and this listener probably became unregistered, so clear it for re-registration.
1704                 mDisplayPortServiceListener = null;
1705             }
1706         }
1707     }
1708 
1709     /**
1710      * Unregisters the given listener if it was previously passed to
1711      * registerDisplayPortAltModeInfoListener.
1712      *
1713      * @param listener          DisplayPortAltModeInfoListener used to register the listener
1714      *                          in registerDisplayPortAltModeInfoListener.
1715      *
1716      * @hide
1717      */
1718     @SystemApi
1719     @RequiresPermission(Manifest.permission.MANAGE_USB)
unregisterDisplayPortAltModeInfoListener( @onNull DisplayPortAltModeInfoListener listener)1720     public void unregisterDisplayPortAltModeInfoListener(
1721             @NonNull DisplayPortAltModeInfoListener listener) {
1722         synchronized (mDisplayPortListenersLock) {
1723             if (mDisplayPortListeners == null) {
1724                 return;
1725             }
1726             mDisplayPortListeners.remove(listener);
1727             if (mDisplayPortListeners.isEmpty()) {
1728                 unregisterDisplayPortAltModeEventsLocked();
1729             }
1730         }
1731         return;
1732     }
1733 
1734     /**
1735      * Sets the component that will handle USB device connection.
1736      * <p>
1737      * Setting component allows to specify external USB host manager to handle use cases, where
1738      * selection dialog for an activity that will handle USB device is undesirable.
1739      * Only system components can call this function, as it requires the MANAGE_USB permission.
1740      *
1741      * @param usbDeviceConnectionHandler The component to handle usb connections,
1742      * {@code null} to unset.
1743      *
1744      * @hide
1745      */
setUsbDeviceConnectionHandler(@ullable ComponentName usbDeviceConnectionHandler)1746     public void setUsbDeviceConnectionHandler(@Nullable ComponentName usbDeviceConnectionHandler) {
1747         try {
1748             mService.setUsbDeviceConnectionHandler(usbDeviceConnectionHandler);
1749         } catch (RemoteException e) {
1750             throw e.rethrowFromSystemServer();
1751         }
1752     }
1753 
1754     /**
1755      * Returns whether the given functions are valid inputs to UsbManager.
1756      * Currently the empty functions or any of MTP, PTP, RNDIS, MIDI, NCM, UVC are accepted.
1757      *
1758      * Only one function may be set at a time, except for RNDIS and NCM, which can be set together
1759      * because from a user perspective they are the same function (tethering).
1760      *
1761      * @return Whether the mask is settable.
1762      *
1763      * @hide
1764      */
areSettableFunctions(long functions)1765     public static boolean areSettableFunctions(long functions) {
1766         return functions == FUNCTION_NONE
1767                 || ((~SETTABLE_FUNCTIONS & functions) == 0
1768                         && ((Long.bitCount(functions) == 1)
1769                                 || (functions == (FUNCTION_RNDIS | FUNCTION_NCM))));
1770     }
1771 
1772     /**
1773      * Converts the given function mask to string. Maintains ordering with respect to init scripts.
1774      *
1775      * @return String representation of given mask
1776      *
1777      * @hide
1778      */
usbFunctionsToString(long functions)1779     public static String usbFunctionsToString(long functions) {
1780         StringJoiner joiner = new StringJoiner(",");
1781         if ((functions & FUNCTION_MTP) != 0) {
1782             joiner.add(UsbManager.USB_FUNCTION_MTP);
1783         }
1784         if ((functions & FUNCTION_PTP) != 0) {
1785             joiner.add(UsbManager.USB_FUNCTION_PTP);
1786         }
1787         if ((functions & FUNCTION_RNDIS) != 0) {
1788             joiner.add(UsbManager.USB_FUNCTION_RNDIS);
1789         }
1790         if ((functions & FUNCTION_MIDI) != 0) {
1791             joiner.add(UsbManager.USB_FUNCTION_MIDI);
1792         }
1793         if ((functions & FUNCTION_ACCESSORY) != 0) {
1794             joiner.add(UsbManager.USB_FUNCTION_ACCESSORY);
1795         }
1796         if ((functions & FUNCTION_AUDIO_SOURCE) != 0) {
1797             joiner.add(UsbManager.USB_FUNCTION_AUDIO_SOURCE);
1798         }
1799         if ((functions & FUNCTION_NCM) != 0) {
1800             joiner.add(UsbManager.USB_FUNCTION_NCM);
1801         }
1802         if ((functions & FUNCTION_UVC) != 0) {
1803             joiner.add(UsbManager.USB_FUNCTION_UVC);
1804         }
1805         if ((functions & FUNCTION_ADB) != 0) {
1806             joiner.add(UsbManager.USB_FUNCTION_ADB);
1807         }
1808         return joiner.toString();
1809     }
1810 
1811     /**
1812      * Parses a string of usb functions that are comma separated.
1813      *
1814      * @return A mask of all valid functions in the string
1815      *
1816      * @hide
1817      */
usbFunctionsFromString(String functions)1818     public static long usbFunctionsFromString(String functions) {
1819         if (functions == null || functions.equals(USB_FUNCTION_NONE)) {
1820             return FUNCTION_NONE;
1821         }
1822         long ret = 0;
1823         for (String function : functions.split(",")) {
1824             if (FUNCTION_NAME_TO_CODE.containsKey(function)) {
1825                 ret |= FUNCTION_NAME_TO_CODE.get(function);
1826             } else if (function.length() > 0) {
1827                 throw new IllegalArgumentException("Invalid usb function " + functions);
1828             }
1829         }
1830         return ret;
1831     }
1832 
1833     /**
1834      * Converts the given integer of USB speed to corresponding bandwidth.
1835      *
1836      * @return a value of USB bandwidth
1837      *
1838      * @hide
1839      */
usbSpeedToBandwidth(int speed)1840     public static int usbSpeedToBandwidth(int speed) {
1841         switch (speed) {
1842             case UsbSpeed.USB4_GEN3_40Gb:
1843                 return USB_DATA_TRANSFER_RATE_40G;
1844             case UsbSpeed.USB4_GEN3_20Gb:
1845                 return USB_DATA_TRANSFER_RATE_20G;
1846             case UsbSpeed.USB4_GEN2_20Gb:
1847                 return USB_DATA_TRANSFER_RATE_20G;
1848             case UsbSpeed.USB4_GEN2_10Gb:
1849                 return USB_DATA_TRANSFER_RATE_10G;
1850             case UsbSpeed.SUPERSPEED_20Gb:
1851                 return USB_DATA_TRANSFER_RATE_20G;
1852             case UsbSpeed.SUPERSPEED_10Gb:
1853                 return USB_DATA_TRANSFER_RATE_10G;
1854             case UsbSpeed.SUPERSPEED:
1855                 return USB_DATA_TRANSFER_RATE_5G;
1856             case UsbSpeed.HIGHSPEED:
1857                 return USB_DATA_TRANSFER_RATE_HIGH_SPEED;
1858             case UsbSpeed.FULLSPEED:
1859                 return USB_DATA_TRANSFER_RATE_FULL_SPEED;
1860             case UsbSpeed.LOWSPEED:
1861                 return USB_DATA_TRANSFER_RATE_LOW_SPEED;
1862             default:
1863                 return USB_DATA_TRANSFER_RATE_UNKNOWN;
1864         }
1865     }
1866 
1867     /**
1868      * Converts the given usb gadgdet hal version to String
1869      *
1870      * @return String representation of Usb Gadget Hal Version
1871      *
1872      * @hide
1873      */
usbGadgetHalVersionToString(int version)1874     public static @NonNull String usbGadgetHalVersionToString(int version) {
1875         String halVersion;
1876 
1877         if (version == GADGET_HAL_V2_0) {
1878             halVersion = GADGET_HAL_VERSION_2_0;
1879         } else if (version == GADGET_HAL_V1_2) {
1880             halVersion = GADGET_HAL_VERSION_1_2;
1881         } else if (version == GADGET_HAL_V1_1) {
1882             halVersion = GADGET_HAL_VERSION_1_1;
1883         } else if (version == GADGET_HAL_V1_0) {
1884             halVersion = GADGET_HAL_VERSION_1_0;
1885         } else {
1886             halVersion = GADGET_HAL_UNKNOWN;
1887         }
1888 
1889         return halVersion;
1890     }
1891 }
1892