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