• 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 android.Manifest;
21 import android.annotation.IntDef;
22 import android.annotation.LongDef;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.annotation.RequiresFeature;
26 import android.annotation.RequiresPermission;
27 import android.annotation.SdkConstant;
28 import android.annotation.SdkConstant.SdkConstantType;
29 import android.annotation.SystemApi;
30 import android.annotation.SystemService;
31 import android.app.PendingIntent;
32 import android.compat.annotation.UnsupportedAppUsage;
33 import android.content.ComponentName;
34 import android.content.Context;
35 import android.content.pm.PackageManager;
36 import android.content.pm.PackageManager.NameNotFoundException;
37 import android.hardware.usb.gadget.V1_0.GadgetFunction;
38 import android.hardware.usb.gadget.V1_2.UsbSpeed;
39 import android.os.Build;
40 import android.os.Bundle;
41 import android.os.ParcelFileDescriptor;
42 import android.os.Process;
43 import android.os.RemoteException;
44 import android.util.Log;
45 
46 import java.util.ArrayList;
47 import java.util.Collections;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.StringJoiner;
52 
53 /**
54  * This class allows you to access the state of USB and communicate with USB devices.
55  * Currently only host mode is supported in the public API.
56  *
57  * <div class="special reference">
58  * <h3>Developer Guides</h3>
59  * <p>For more information about communicating with USB hardware, read the
60  * <a href="{@docRoot}guide/topics/connectivity/usb/index.html">USB developer guide</a>.</p>
61  * </div>
62  */
63 @SystemService(Context.USB_SERVICE)
64 public class UsbManager {
65     private static final String TAG = "UsbManager";
66 
67    /**
68      * Broadcast Action:  A sticky broadcast for USB state change events when in device mode.
69      *
70      * This is a sticky broadcast for clients that includes USB connected/disconnected state,
71      * <ul>
72      * <li> {@link #USB_CONNECTED} boolean indicating whether USB is connected or disconnected.
73      * <li> {@link #USB_HOST_CONNECTED} boolean indicating whether USB is connected or
74      *     disconnected as host.
75      * <li> {@link #USB_CONFIGURED} boolean indicating whether USB is configured.
76      * currently zero if not configured, one for configured.
77      * <li> {@link #USB_FUNCTION_ADB} boolean extra indicating whether the
78      * adb function is enabled
79      * <li> {@link #USB_FUNCTION_RNDIS} boolean extra indicating whether the
80      * RNDIS ethernet function is enabled
81      * <li> {@link #USB_FUNCTION_MTP} boolean extra indicating whether the
82      * MTP function is enabled
83      * <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the
84      * PTP function is enabled
85      * <li> {@link #USB_FUNCTION_ACCESSORY} boolean extra indicating whether the
86      * accessory function is enabled
87      * <li> {@link #USB_FUNCTION_AUDIO_SOURCE} boolean extra indicating whether the
88      * audio source function is enabled
89      * <li> {@link #USB_FUNCTION_MIDI} boolean extra indicating whether the
90      * MIDI function is enabled
91      * </ul>
92      * If the sticky intent has not been found, that indicates USB is disconnected,
93      * USB is not configued, MTP function is enabled, and all the other functions are disabled.
94      *
95      * {@hide}
96      */
97     @SystemApi
98     public static final String ACTION_USB_STATE =
99             "android.hardware.usb.action.USB_STATE";
100 
101     /**
102      * Broadcast Action: A broadcast for USB port changes.
103      *
104      * This intent is sent when a USB port is added, removed, or changes state.
105      *
106      * @hide
107      */
108     @SystemApi
109     @RequiresPermission(Manifest.permission.MANAGE_USB)
110     public static final String ACTION_USB_PORT_CHANGED =
111             "android.hardware.usb.action.USB_PORT_CHANGED";
112 
113    /**
114      * Activity intent sent when user attaches a USB device.
115      *
116      * This intent is sent when a USB device is attached to the USB bus when in host mode.
117      * <ul>
118      * <li> {@link #EXTRA_DEVICE} containing the {@link android.hardware.usb.UsbDevice}
119      * for the attached device
120      * </ul>
121      */
122     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
123     public static final String ACTION_USB_DEVICE_ATTACHED =
124             "android.hardware.usb.action.USB_DEVICE_ATTACHED";
125 
126    /**
127      * Broadcast Action:  A broadcast for USB device detached event.
128      *
129      * This intent is sent when a USB device is detached from the USB bus when in host mode.
130      * <ul>
131      * <li> {@link #EXTRA_DEVICE} containing the {@link android.hardware.usb.UsbDevice}
132      * for the detached device
133      * </ul>
134      */
135     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
136     public static final String ACTION_USB_DEVICE_DETACHED =
137             "android.hardware.usb.action.USB_DEVICE_DETACHED";
138 
139    /**
140      * Activity intent sent when user attaches a USB accessory.
141      *
142      * <ul>
143      * <li> {@link #EXTRA_ACCESSORY} containing the {@link android.hardware.usb.UsbAccessory}
144      * for the attached accessory
145      * </ul>
146      */
147     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
148     public static final String ACTION_USB_ACCESSORY_ATTACHED =
149             "android.hardware.usb.action.USB_ACCESSORY_ATTACHED";
150 
151    /**
152      * Broadcast Action:  A broadcast for USB accessory detached event.
153      *
154      * This intent is sent when a USB accessory is detached.
155      * <ul>
156      * <li> {@link #EXTRA_ACCESSORY} containing the {@link UsbAccessory}
157      * for the attached accessory that was detached
158      * </ul>
159      */
160     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
161     public static final String ACTION_USB_ACCESSORY_DETACHED =
162             "android.hardware.usb.action.USB_ACCESSORY_DETACHED";
163 
164     /**
165      * Broadcast Action:  A broadcast for USB accessory handshaking information delivery
166      *
167      * This intent is sent when a USB accessory connect attempt
168      *
169      * <p>For more information about communicating with USB accessory handshake, refer to
170      * <a href="https://source.android.com/devices/accessories/aoa">AOA</a> developer guide.</p>
171      *
172      * {@hide}
173      */
174     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
175     @SystemApi
176     @RequiresPermission(Manifest.permission.MANAGE_USB)
177     public static final String ACTION_USB_ACCESSORY_HANDSHAKE =
178             "android.hardware.usb.action.USB_ACCESSORY_HANDSHAKE";
179 
180     /**
181      * Boolean extra indicating whether USB is connected or disconnected.
182      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
183      *
184      * {@hide}
185      */
186     @SystemApi
187     public static final String USB_CONNECTED = "connected";
188 
189     /**
190      * Boolean extra indicating whether USB is connected or disconnected as host.
191      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
192      *
193      * {@hide}
194      */
195     public static final String USB_HOST_CONNECTED = "host_connected";
196 
197     /**
198      * Boolean extra indicating whether USB is configured.
199      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
200      *
201      * {@hide}
202      */
203     @SystemApi
204     public static final String USB_CONFIGURED = "configured";
205 
206     /**
207      * Boolean extra indicating whether confidential user data, such as photos, should be
208      * made available on the USB connection. This variable will only be set when the user
209      * has explicitly asked for this data to be unlocked.
210      * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
211      *
212      * {@hide}
213      */
214     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
215     public static final String USB_DATA_UNLOCKED = "unlocked";
216 
217     /**
218      * A placeholder indicating that no USB function is being specified.
219      * Used for compatibility with old init scripts to indicate no functions vs. charging function.
220      *
221      * {@hide}
222      */
223     @UnsupportedAppUsage
224     public static final String USB_FUNCTION_NONE = "none";
225 
226     /**
227      * Name of the adb USB function.
228      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
229      *
230      * {@hide}
231      */
232     public static final String USB_FUNCTION_ADB = "adb";
233 
234     /**
235      * Name of the RNDIS ethernet USB function.
236      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
237      *
238      * {@hide}
239      */
240     @SystemApi
241     public static final String USB_FUNCTION_RNDIS = "rndis";
242 
243     /**
244      * Name of the MTP USB function.
245      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
246      *
247      * {@hide}
248      */
249     public static final String USB_FUNCTION_MTP = "mtp";
250 
251     /**
252      * Name of the PTP USB function.
253      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
254      *
255      * {@hide}
256      */
257     public static final String USB_FUNCTION_PTP = "ptp";
258 
259     /**
260      * Name of the audio source USB function.
261      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
262      *
263      * {@hide}
264      */
265     public static final String USB_FUNCTION_AUDIO_SOURCE = "audio_source";
266 
267     /**
268      * Name of the MIDI USB function.
269      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
270      *
271      * {@hide}
272      */
273     public static final String USB_FUNCTION_MIDI = "midi";
274 
275     /**
276      * Name of the Accessory USB function.
277      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
278      *
279      * {@hide}
280      */
281     public static final String USB_FUNCTION_ACCESSORY = "accessory";
282 
283     /**
284      * Name of the NCM USB function.
285      * Used in extras for the {@link #ACTION_USB_STATE} broadcast
286      *
287      * {@hide}
288      */
289     @SystemApi
290     public static final String USB_FUNCTION_NCM = "ncm";
291 
292     /**
293      * Name of Gadget Hal Not Present;
294      *
295      * {@hide}
296      */
297     public static final String GADGET_HAL_UNKNOWN = "unknown";
298 
299     /**
300      * Name of the USB Gadget Hal Version v1.0;
301      *
302      * {@hide}
303      */
304     public static final String GADGET_HAL_VERSION_1_0 = "V1_0";
305 
306     /**
307      * Name of the USB Gadget Hal Version v1.1;
308      *
309      * {@hide}
310      */
311     public static final String GADGET_HAL_VERSION_1_1 = "V1_1";
312 
313     /**
314      * Name of the USB Gadget Hal Version v1.2;
315      *
316      * {@hide}
317      */
318     public static final String GADGET_HAL_VERSION_1_2 = "V1_2";
319 
320     /**
321      * Name of extra for {@link #ACTION_USB_PORT_CHANGED}
322      * containing the {@link UsbPort} object for the port.
323      *
324      * @hide
325      */
326     public static final String EXTRA_PORT = "port";
327 
328     /**
329      * Name of extra for {@link #ACTION_USB_PORT_CHANGED}
330      * containing the {@link UsbPortStatus} object for the port, or null if the port
331      * was removed.
332      *
333      * @hide
334      */
335     public static final String EXTRA_PORT_STATUS = "portStatus";
336 
337     /**
338      * Name of extra for {@link #ACTION_USB_DEVICE_ATTACHED} and
339      * {@link #ACTION_USB_DEVICE_DETACHED} broadcasts
340      * containing the {@link UsbDevice} object for the device.
341      */
342     public static final String EXTRA_DEVICE = "device";
343 
344     /**
345      * Name of extra for {@link #ACTION_USB_ACCESSORY_ATTACHED} and
346      * {@link #ACTION_USB_ACCESSORY_DETACHED} broadcasts
347      * containing the {@link UsbAccessory} object for the accessory.
348      */
349     public static final String EXTRA_ACCESSORY = "accessory";
350 
351     /**
352      * A long extra indicating ms from boot to get get_protocol UEvent
353      * This is obtained with SystemClock.elapsedRealtime()
354      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts.
355      *
356      * {@hide}
357      */
358     @SystemApi
359     public static final String EXTRA_ACCESSORY_UEVENT_TIME =
360             "android.hardware.usb.extra.ACCESSORY_UEVENT_TIME";
361 
362     /**
363      * An integer extra indicating numbers of send string during handshake
364      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts
365      *
366      * <p>For more information about control request with identifying string information
367      * between communicating with USB accessory handshake, refer to
368      * <a href="https://source.android.com/devices/accessories/aoa">AOA</a> developer guide.</p>
369      *
370      * {@hide}
371      */
372     @SystemApi
373     public static final String EXTRA_ACCESSORY_STRING_COUNT =
374             "android.hardware.usb.extra.ACCESSORY_STRING_COUNT";
375 
376     /**
377      * Boolean extra indicating whether got start accessory or not
378      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts.
379      *
380      * {@hide}
381      */
382     @SystemApi
383     public static final String EXTRA_ACCESSORY_START =
384             "android.hardware.usb.extra.ACCESSORY_START";
385 
386     /**
387      * A long extra indicating ms from boot to sent {@link #ACTION_USB_ACCESSORY_HANDSHAKE}
388      * This is obtained with SystemClock.elapsedRealtime()
389      * Used in extras for {@link #ACTION_USB_ACCESSORY_HANDSHAKE} broadcasts.
390      *
391      * {@hide}
392      */
393     @SystemApi
394     public static final String EXTRA_ACCESSORY_HANDSHAKE_END =
395             "android.hardware.usb.extra.ACCESSORY_HANDSHAKE_END";
396 
397     /**
398      * Name of extra added to the {@link android.app.PendingIntent}
399      * passed into {@link #requestPermission(UsbDevice, PendingIntent)}
400      * or {@link #requestPermission(UsbAccessory, PendingIntent)}
401      * containing a boolean value indicating whether the user granted permission or not.
402      */
403     public static final String EXTRA_PERMISSION_GRANTED = "permission";
404 
405     /**
406      * Name of extra added to start systemui.usb.UsbPermissionActivity
407      * containing package name of the app which requests USB permission.
408      *
409      * @hide
410      */
411     public static final String EXTRA_PACKAGE = "android.hardware.usb.extra.PACKAGE";
412 
413     /**
414      * Name of extra added to start systemui.usb.UsbPermissionActivity
415      * containing the whether the app which requests USB permission can be set as default handler
416      * for USB device attach event or USB accessory attach event or not.
417      *
418      * @hide
419      */
420     public static final String EXTRA_CAN_BE_DEFAULT = "android.hardware.usb.extra.CAN_BE_DEFAULT";
421 
422     /**
423      * The Value for USB gadget hal is not presented.
424      *
425      * {@hide}
426      */
427     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
428     public static final int GADGET_HAL_NOT_SUPPORTED = -1;
429 
430     /**
431      * Value for Gadget Hal Version v1.0.
432      *
433      * {@hide}
434      */
435     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
436     public static final int GADGET_HAL_V1_0 = 10;
437 
438     /**
439      * Value for Gadget Hal Version v1.1.
440      *
441      * {@hide}
442      */
443     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
444     public static final int GADGET_HAL_V1_1 = 11;
445 
446     /**
447      * Value for Gadget Hal Version v1.2.
448      *
449      * {@hide}
450      */
451     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
452     public static final int GADGET_HAL_V1_2 = 12;
453 
454     /**
455      * Value for USB_STATE is not configured.
456      *
457      * {@hide}
458      */
459     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
460     public static final int USB_DATA_TRANSFER_RATE_UNKNOWN = -1;
461 
462     /**
463      * Value for USB Transfer Rate of Low Speed in Mbps (real value is 1.5Mbps).
464      *
465      * {@hide}
466      */
467     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
468     public static final int USB_DATA_TRANSFER_RATE_LOW_SPEED = 2;
469 
470     /**
471      * Value for USB Transfer Rate of Full Speed in Mbps.
472      *
473      * {@hide}
474      */
475     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
476     public static final int USB_DATA_TRANSFER_RATE_FULL_SPEED = 12;
477 
478     /**
479      * Value for USB Transfer Rate of High Speed in Mbps.
480      *
481      * {@hide}
482      */
483     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
484     public static final int USB_DATA_TRANSFER_RATE_HIGH_SPEED = 480;
485 
486     /**
487      * Value for USB Transfer Rate of Super Speed in Mbps.
488      *
489      * {@hide}
490      */
491     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
492     public static final int USB_DATA_TRANSFER_RATE_5G = 5 * 1024;
493 
494     /**
495      * Value for USB Transfer Rate of 10G.
496      *
497      * {@hide}
498      */
499     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
500     public static final int USB_DATA_TRANSFER_RATE_10G = 10 * 1024;
501 
502     /**
503      * Value for USB Transfer Rate of 20G.
504      *
505      * {@hide}
506      */
507     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
508     public static final int USB_DATA_TRANSFER_RATE_20G = 20 * 1024;
509 
510     /**
511      * Value for USB Transfer Rate of 40G.
512      *
513      * {@hide}
514      */
515     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
516     public static final int USB_DATA_TRANSFER_RATE_40G = 40 * 1024;
517 
518     /**
519      * The Value for USB hal is not presented.
520      *
521      * {@hide}
522      */
523     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
524     public static final int USB_HAL_NOT_SUPPORTED = -1;
525 
526     /**
527      * Value for USB Hal Version v1.0.
528      *
529      * {@hide}
530      */
531     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
532     public static final int USB_HAL_V1_0 = 10;
533 
534     /**
535      * Value for USB Hal Version v1.1.
536      *
537      * {@hide}
538      */
539     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
540     public static final int USB_HAL_V1_1 = 11;
541 
542     /**
543      * Value for USB Hal Version v1.2.
544      *
545      * {@hide}
546      */
547     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
548     public static final int USB_HAL_V1_2 = 12;
549 
550     /**
551      * Value for USB Hal Version v1.3.
552      *
553      * {@hide}
554      */
555     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
556     public static final int USB_HAL_V1_3 = 13;
557 
558     /**
559      * Code for the charging usb function. Passed into {@link #setCurrentFunctions(long)}
560      * {@hide}
561      */
562     @SystemApi
563     public static final long FUNCTION_NONE = 0;
564 
565     /**
566      * Code for the mtp usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
567      * {@hide}
568      */
569     @SystemApi
570     public static final long FUNCTION_MTP = GadgetFunction.MTP;
571 
572     /**
573      * Code for the ptp usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
574      * {@hide}
575      */
576     @SystemApi
577     public static final long FUNCTION_PTP = GadgetFunction.PTP;
578 
579     /**
580      * Code for the rndis usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
581      * {@hide}
582      */
583     @SystemApi
584     public static final long FUNCTION_RNDIS = GadgetFunction.RNDIS;
585 
586     /**
587      * Code for the midi usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
588      * {@hide}
589      */
590     @SystemApi
591     public static final long FUNCTION_MIDI = GadgetFunction.MIDI;
592 
593     /**
594      * Code for the accessory usb function.
595      * {@hide}
596      */
597     @SystemApi
598     public static final long FUNCTION_ACCESSORY = GadgetFunction.ACCESSORY;
599 
600     /**
601      * Code for the audio source usb function.
602      * {@hide}
603      */
604     @SystemApi
605     public static final long FUNCTION_AUDIO_SOURCE = GadgetFunction.AUDIO_SOURCE;
606 
607     /**
608      * Code for the adb usb function.
609      * {@hide}
610      */
611     @SystemApi
612     public static final long FUNCTION_ADB = GadgetFunction.ADB;
613 
614     /**
615      * Code for the ncm source usb function.
616      * {@hide}
617      */
618     @SystemApi
619     public static final long FUNCTION_NCM = 1 << 10;
620 
621     private static final long SETTABLE_FUNCTIONS = FUNCTION_MTP | FUNCTION_PTP | FUNCTION_RNDIS
622             | FUNCTION_MIDI | FUNCTION_NCM;
623 
624     private static final Map<String, Long> FUNCTION_NAME_TO_CODE = new HashMap<>();
625 
626     static {
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MTP, FUNCTION_MTP)627         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MTP, FUNCTION_MTP);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_PTP, FUNCTION_PTP)628         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_PTP, FUNCTION_PTP);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_RNDIS, FUNCTION_RNDIS)629         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_RNDIS, FUNCTION_RNDIS);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MIDI, FUNCTION_MIDI)630         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MIDI, FUNCTION_MIDI);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ACCESSORY, FUNCTION_ACCESSORY)631         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ACCESSORY, FUNCTION_ACCESSORY);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_AUDIO_SOURCE, FUNCTION_AUDIO_SOURCE)632         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_AUDIO_SOURCE, FUNCTION_AUDIO_SOURCE);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ADB, FUNCTION_ADB)633         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ADB, FUNCTION_ADB);
FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_NCM, FUNCTION_NCM)634         FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_NCM, FUNCTION_NCM);
635     }
636 
637     /** @hide */
638     @LongDef(flag = true, prefix = { "FUNCTION_" }, value = {
639             FUNCTION_NONE,
640             FUNCTION_MTP,
641             FUNCTION_PTP,
642             FUNCTION_RNDIS,
643             FUNCTION_MIDI,
644             FUNCTION_ACCESSORY,
645             FUNCTION_AUDIO_SOURCE,
646             FUNCTION_ADB,
647             FUNCTION_NCM,
648     })
649     public @interface UsbFunctionMode {}
650 
651     /** @hide */
652     @IntDef(prefix = { "GADGET_HAL_" }, value = {
653             GADGET_HAL_NOT_SUPPORTED,
654             GADGET_HAL_V1_0,
655             GADGET_HAL_V1_1,
656             GADGET_HAL_V1_2,
657     })
658     public @interface UsbGadgetHalVersion {}
659 
660     /** @hide */
661     @IntDef(prefix = { "USB_HAL_" }, value = {
662             USB_HAL_NOT_SUPPORTED,
663             USB_HAL_V1_0,
664             USB_HAL_V1_1,
665             USB_HAL_V1_2,
666             USB_HAL_V1_3,
667     })
668     public @interface UsbHalVersion {}
669 
670     private final Context mContext;
671     private final IUsbManager mService;
672 
673     /**
674      * {@hide}
675      */
676     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
UsbManager(Context context, IUsbManager service)677     public UsbManager(Context context, IUsbManager service) {
678         mContext = context;
679         mService = service;
680     }
681 
682     /**
683      * Returns a HashMap containing all USB devices currently attached.
684      * USB device name is the key for the returned HashMap.
685      * The result will be empty if no devices are attached, or if
686      * USB host mode is inactive or unsupported.
687      *
688      * @return HashMap containing all connected USB devices.
689      */
690     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
getDeviceList()691     public HashMap<String,UsbDevice> getDeviceList() {
692         HashMap<String,UsbDevice> result = new HashMap<String,UsbDevice>();
693         if (mService == null) {
694             return result;
695         }
696         Bundle bundle = new Bundle();
697         try {
698             mService.getDeviceList(bundle);
699             for (String name : bundle.keySet()) {
700                 result.put(name, (UsbDevice)bundle.get(name));
701             }
702             return result;
703         } catch (RemoteException e) {
704             throw e.rethrowFromSystemServer();
705         }
706     }
707 
708     /**
709      * Opens the device so it can be used to send and receive
710      * data using {@link android.hardware.usb.UsbRequest}.
711      *
712      * @param device the device to open
713      * @return a {@link UsbDeviceConnection}, or {@code null} if open failed
714      */
715     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
openDevice(UsbDevice device)716     public UsbDeviceConnection openDevice(UsbDevice device) {
717         try {
718             String deviceName = device.getDeviceName();
719             ParcelFileDescriptor pfd = mService.openDevice(deviceName, mContext.getPackageName());
720             if (pfd != null) {
721                 UsbDeviceConnection connection = new UsbDeviceConnection(device);
722                 boolean result = connection.open(deviceName, pfd, mContext);
723                 pfd.close();
724                 if (result) {
725                     return connection;
726                 }
727             }
728         } catch (Exception e) {
729             Log.e(TAG, "exception in UsbManager.openDevice", e);
730         }
731         return null;
732     }
733 
734     /**
735      * Returns a list of currently attached USB accessories.
736      * (in the current implementation there can be at most one)
737      *
738      * @return list of USB accessories, or null if none are attached.
739      */
740     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
getAccessoryList()741     public UsbAccessory[] getAccessoryList() {
742         if (mService == null) {
743             return null;
744         }
745         try {
746             UsbAccessory accessory = mService.getCurrentAccessory();
747             if (accessory == null) {
748                 return null;
749             } else {
750                 return new UsbAccessory[] { accessory };
751             }
752         } catch (RemoteException e) {
753             throw e.rethrowFromSystemServer();
754         }
755     }
756 
757     /**
758      * Opens a file descriptor for reading and writing data to the USB accessory.
759      *
760      * <p>If data is read from the {@link java.io.InputStream} created from this file descriptor all
761      * data of a USB transfer should be read at once. If only a partial request is read the rest of
762      * the transfer is dropped.
763      *
764      * @param accessory the USB accessory to open
765      * @return file descriptor, or null if the accessory could not be opened.
766      */
767     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
openAccessory(UsbAccessory accessory)768     public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
769         try {
770             return mService.openAccessory(accessory);
771         } catch (RemoteException e) {
772             throw e.rethrowFromSystemServer();
773         }
774     }
775 
776     /**
777      * Gets the functionfs control file descriptor for the given function, with
778      * the usb descriptors and strings already written. The file descriptor is used
779      * by the function implementation to handle events and control requests.
780      *
781      * @param function to get control fd for. Currently {@link #FUNCTION_MTP} and
782      * {@link #FUNCTION_PTP} are supported.
783      * @return A ParcelFileDescriptor holding the valid fd, or null if the fd was not found.
784      *
785      * {@hide}
786      */
getControlFd(long function)787     public ParcelFileDescriptor getControlFd(long function) {
788         try {
789             return mService.getControlFd(function);
790         } catch (RemoteException e) {
791             throw e.rethrowFromSystemServer();
792         }
793     }
794 
795     /**
796      * Returns true if the caller has permission to access the device.
797      * Permission might have been granted temporarily via
798      * {@link #requestPermission(UsbDevice, PendingIntent)} or
799      * by the user choosing the caller as the default application for the device.
800      * Permission for USB devices of class {@link UsbConstants#USB_CLASS_VIDEO} for clients that
801      * target SDK {@link android.os.Build.VERSION_CODES#P} and above can be granted only if they
802      * have additionally the {@link android.Manifest.permission#CAMERA} permission.
803      *
804      * @param device to check permissions for
805      * @return true if caller has permission
806      */
807     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
hasPermission(UsbDevice device)808     public boolean hasPermission(UsbDevice device) {
809         if (mService == null) {
810             return false;
811         }
812         try {
813             return mService.hasDevicePermission(device, mContext.getPackageName());
814         } catch (RemoteException e) {
815             throw e.rethrowFromSystemServer();
816         }
817     }
818 
819     /**
820      * Returns true if the caller has permission to access the accessory.
821      * Permission might have been granted temporarily via
822      * {@link #requestPermission(UsbAccessory, PendingIntent)} or
823      * by the user choosing the caller as the default application for the accessory.
824      *
825      * @param accessory to check permissions for
826      * @return true if caller has permission
827      */
828     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
hasPermission(UsbAccessory accessory)829     public boolean hasPermission(UsbAccessory accessory) {
830         if (mService == null) {
831             return false;
832         }
833         try {
834             return mService.hasAccessoryPermission(accessory);
835         } catch (RemoteException e) {
836             throw e.rethrowFromSystemServer();
837         }
838     }
839 
840     /**
841      * Requests temporary permission for the given package to access the device.
842      * This may result in a system dialog being displayed to the user
843      * if permission had not already been granted.
844      * Success or failure is returned via the {@link android.app.PendingIntent} pi.
845      * If successful, this grants the caller permission to access the device only
846      * until the device is disconnected.
847      *
848      * The following extras will be added to pi:
849      * <ul>
850      * <li> {@link #EXTRA_DEVICE} containing the device passed into this call
851      * <li> {@link #EXTRA_PERMISSION_GRANTED} containing boolean indicating whether
852      * permission was granted by the user
853      * </ul>
854      *
855      * Permission for USB devices of class {@link UsbConstants#USB_CLASS_VIDEO} for clients that
856      * target SDK {@link android.os.Build.VERSION_CODES#P} and above can be granted only if they
857      * have additionally the {@link android.Manifest.permission#CAMERA} permission.
858      *
859      * @param device to request permissions for
860      * @param pi PendingIntent for returning result
861      */
862     @RequiresFeature(PackageManager.FEATURE_USB_HOST)
requestPermission(UsbDevice device, PendingIntent pi)863     public void requestPermission(UsbDevice device, PendingIntent pi) {
864         try {
865             mService.requestDevicePermission(device, mContext.getPackageName(), pi);
866         } catch (RemoteException e) {
867             throw e.rethrowFromSystemServer();
868         }
869     }
870 
871     /**
872      * Requests temporary permission for the given package to access the accessory.
873      * This may result in a system dialog being displayed to the user
874      * if permission had not already been granted.
875      * Success or failure is returned via the {@link android.app.PendingIntent} pi.
876      * If successful, this grants the caller permission to access the accessory only
877      * until the device is disconnected.
878      *
879      * The following extras will be added to pi:
880      * <ul>
881      * <li> {@link #EXTRA_ACCESSORY} containing the accessory passed into this call
882      * <li> {@link #EXTRA_PERMISSION_GRANTED} containing boolean indicating whether
883      * permission was granted by the user
884      * </ul>
885      *
886      * @param accessory to request permissions for
887      * @param pi PendingIntent for returning result
888      */
889     @RequiresFeature(PackageManager.FEATURE_USB_ACCESSORY)
requestPermission(UsbAccessory accessory, PendingIntent pi)890     public void requestPermission(UsbAccessory accessory, PendingIntent pi) {
891         try {
892             mService.requestAccessoryPermission(accessory, mContext.getPackageName(), pi);
893         } catch (RemoteException e) {
894             throw e.rethrowFromSystemServer();
895         }
896     }
897 
898     /**
899      * Grants permission for USB device without showing system dialog.
900      * Only system components can call this function.
901      * @param device to request permissions for
902      *
903      * {@hide}
904      */
grantPermission(UsbDevice device)905     public void grantPermission(UsbDevice device) {
906         grantPermission(device, Process.myUid());
907     }
908 
909     /**
910      * Grants permission for USB device to given uid without showing system dialog.
911      * Only system components can call this function.
912      * @param device to request permissions for
913      * @uid uid to give permission
914      *
915      * {@hide}
916      */
grantPermission(UsbDevice device, int uid)917     public void grantPermission(UsbDevice device, int uid) {
918         try {
919             mService.grantDevicePermission(device, uid);
920         } catch (RemoteException e) {
921             throw e.rethrowFromSystemServer();
922         }
923     }
924 
925     /**
926      * Grants permission to specified package for USB device without showing system dialog.
927      * Only system components can call this function, as it requires the MANAGE_USB permission.
928      * @param device to request permissions for
929      * @param packageName of package to grant permissions
930      *
931      * {@hide}
932      */
933     @SystemApi
934     @RequiresPermission(Manifest.permission.MANAGE_USB)
grantPermission(UsbDevice device, String packageName)935     public void grantPermission(UsbDevice device, String packageName) {
936         try {
937             int uid = mContext.getPackageManager()
938                 .getPackageUidAsUser(packageName, mContext.getUserId());
939             grantPermission(device, uid);
940         } catch (NameNotFoundException e) {
941             Log.e(TAG, "Package " + packageName + " not found.", e);
942         }
943     }
944 
945     /**
946      * Returns true if the specified USB function is currently enabled when in device mode.
947      * <p>
948      * USB functions represent interfaces which are published to the host to access
949      * services offered by the device.
950      * </p>
951      *
952      * @deprecated use getCurrentFunctions() instead.
953      * @param function name of the USB function
954      * @return true if the USB function is enabled
955      *
956      * {@hide}
957      */
958     @Deprecated
959     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
isFunctionEnabled(String function)960     public boolean isFunctionEnabled(String function) {
961         try {
962             return mService.isFunctionEnabled(function);
963         } catch (RemoteException e) {
964             throw e.rethrowFromSystemServer();
965         }
966     }
967 
968     /**
969      * Sets the current USB functions when in device mode.
970      * <p>
971      * USB functions represent interfaces which are published to the host to access
972      * services offered by the device.
973      * </p><p>
974      * This method is intended to select among primary USB functions.  The system may
975      * automatically activate additional functions such as {@link #USB_FUNCTION_ADB}
976      * or {@link #USB_FUNCTION_ACCESSORY} based on other settings and states.
977      * </p><p>
978      * An argument of 0 indicates that the device is charging, and can pick any
979      * appropriate function for that purpose.
980      * </p><p>
981      * Note: This function is asynchronous and may fail silently without applying
982      * the requested changes.
983      * </p>
984      *
985      * @param functions the USB function(s) to set, as a bitwise mask.
986      *                  Must satisfy {@link UsbManager#areSettableFunctions}
987      *
988      * {@hide}
989      */
990     @SystemApi
991     @RequiresPermission(Manifest.permission.MANAGE_USB)
setCurrentFunctions(@sbFunctionMode long functions)992     public void setCurrentFunctions(@UsbFunctionMode long functions) {
993         try {
994             mService.setCurrentFunctions(functions);
995         } catch (RemoteException e) {
996             throw e.rethrowFromSystemServer();
997         }
998     }
999 
1000     /**
1001      * Sets the current USB functions when in device mode.
1002      *
1003      * @deprecated use setCurrentFunctions(long) instead.
1004      * @param functions the USB function(s) to set.
1005      * @param usbDataUnlocked unused
1006 
1007      * {@hide}
1008      */
1009     @Deprecated
1010     @UnsupportedAppUsage
setCurrentFunction(String functions, boolean usbDataUnlocked)1011     public void setCurrentFunction(String functions, boolean usbDataUnlocked) {
1012         try {
1013             mService.setCurrentFunction(functions, usbDataUnlocked);
1014         } catch (RemoteException e) {
1015             throw e.rethrowFromSystemServer();
1016         }
1017     }
1018 
1019     /**
1020      * Returns the current USB functions in device mode.
1021      * <p>
1022      * This function returns the state of primary USB functions and can return a
1023      * mask containing any usb function(s) except for ADB.
1024      * </p>
1025      *
1026      * @return The currently enabled functions, in a bitwise mask.
1027      * A zero mask indicates that the current function is the charging function.
1028      *
1029      * {@hide}
1030      */
1031     @SystemApi
1032     @RequiresPermission(Manifest.permission.MANAGE_USB)
getCurrentFunctions()1033     public long getCurrentFunctions() {
1034         try {
1035             return mService.getCurrentFunctions();
1036         } catch (RemoteException e) {
1037             throw e.rethrowFromSystemServer();
1038         }
1039     }
1040 
1041     /**
1042      * Sets the screen unlocked functions, which are persisted and set as the current functions
1043      * whenever the screen is unlocked.
1044      * <p>
1045      * A zero mask has the effect of switching off this feature, so functions
1046      * no longer change on screen unlock.
1047      * </p><p>
1048      * Note: When the screen is on, this method will apply given functions as current functions,
1049      * which is asynchronous and may fail silently without applying the requested changes.
1050      * </p>
1051      *
1052      * @param functions functions to set, in a bitwise mask.
1053      *                  Must satisfy {@link UsbManager#areSettableFunctions}
1054      *
1055      * {@hide}
1056      */
setScreenUnlockedFunctions(long functions)1057     public void setScreenUnlockedFunctions(long functions) {
1058         try {
1059             mService.setScreenUnlockedFunctions(functions);
1060         } catch (RemoteException e) {
1061             throw e.rethrowFromSystemServer();
1062         }
1063     }
1064 
1065     /**
1066      * Gets the current screen unlocked functions.
1067      *
1068      * @return The currently set screen enabled functions.
1069      * A zero mask indicates that the screen unlocked functions feature is not enabled.
1070      *
1071      * {@hide}
1072      */
getScreenUnlockedFunctions()1073     public long getScreenUnlockedFunctions() {
1074         try {
1075             return mService.getScreenUnlockedFunctions();
1076         } catch (RemoteException e) {
1077             throw e.rethrowFromSystemServer();
1078         }
1079     }
1080 
1081     /**
1082      * Get the Current USB Bandwidth.
1083      * <p>
1084      * This function returns the current USB bandwidth through USB Gadget HAL.
1085      * It should be used when Android device is in USB peripheral mode and
1086      * connects to a USB host. If USB state is not configued, API will return
1087      * {@value #USB_DATA_TRANSFER_RATE_UNKNOWN}. In addition, the unit of the
1088      * return value is Mbps.
1089      * </p>
1090      *
1091      * @return The value of currently USB Bandwidth.
1092      *
1093      * {@hide}
1094      */
1095     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1096     @RequiresPermission(Manifest.permission.MANAGE_USB)
getUsbBandwidthMbps()1097     public int getUsbBandwidthMbps() {
1098         int usbSpeed;
1099 
1100         try {
1101             usbSpeed = mService.getCurrentUsbSpeed();
1102         } catch (RemoteException e) {
1103             throw e.rethrowFromSystemServer();
1104         }
1105 
1106         return usbSpeedToBandwidth(usbSpeed);
1107     }
1108 
1109     /**
1110      * Get the Current Gadget Hal Version.
1111      * <p>
1112      * This function returns the current Gadget Hal Version.
1113      * </p>
1114      *
1115      * @return a integer {@code GADGET_HAL_*} represent hal version.
1116      *
1117      * {@hide}
1118      */
1119     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1120     @RequiresPermission(Manifest.permission.MANAGE_USB)
getGadgetHalVersion()1121     public @UsbGadgetHalVersion int getGadgetHalVersion() {
1122         try {
1123             return mService.getGadgetHalVersion();
1124         } catch (RemoteException e) {
1125             throw e.rethrowFromSystemServer();
1126         }
1127     }
1128 
1129     /**
1130      * Get the Current USB Hal Version.
1131      * <p>
1132      * This function returns the current USB Hal Version.
1133      * </p>
1134      *
1135      * @return a integer {@code USB_HAL_*} represent hal version.
1136      *
1137      * {@hide}
1138      */
1139     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1140     @RequiresPermission(Manifest.permission.MANAGE_USB)
getUsbHalVersion()1141     public @UsbHalVersion int getUsbHalVersion() {
1142         try {
1143             return mService.getUsbHalVersion();
1144         } catch (RemoteException e) {
1145             throw e.rethrowFromSystemServer();
1146         }
1147     }
1148 
1149     /**
1150      * Resets the USB Gadget.
1151      * <p>
1152      * Performs USB data stack reset through USB Gadget HAL.
1153      * It will force USB data connection reset. The connection will disconnect and reconnect.
1154      * </p>
1155      *
1156      * @hide
1157      */
1158     @SystemApi
1159     @RequiresPermission(Manifest.permission.MANAGE_USB)
resetUsbGadget()1160     public void resetUsbGadget() {
1161         try {
1162             mService.resetUsbGadget();
1163         } catch (RemoteException e) {
1164             throw e.rethrowFromSystemServer();
1165         }
1166     }
1167 
1168     /**
1169      * Enable/Disable the USB data signaling.
1170      * <p>
1171      * Enables/Disables USB data path in all the USB ports.
1172      * It will force to stop or restore USB data signaling.
1173      * </p>
1174      *
1175      * @param enable enable or disable USB data signaling
1176      * @return true enable or disable USB data successfully
1177      *         false if something wrong
1178      *
1179      * @hide
1180      */
1181     @RequiresPermission(Manifest.permission.MANAGE_USB)
enableUsbDataSignal(boolean enable)1182     public boolean enableUsbDataSignal(boolean enable) {
1183         try {
1184             return mService.enableUsbDataSignal(enable);
1185         } catch (RemoteException e) {
1186             throw e.rethrowFromSystemServer();
1187         }
1188     }
1189 
1190     /**
1191      * Returns a list of physical USB ports on the device.
1192      * <p>
1193      * This list is guaranteed to contain all dual-role USB Type C ports but it might
1194      * be missing other ports depending on whether the kernel USB drivers have been
1195      * updated to publish all of the device's ports through the new "dual_role_usb"
1196      * device class (which supports all types of ports despite its name).
1197      * </p>
1198      *
1199      * @return The list of USB ports
1200      *
1201      * @hide
1202      */
1203     @SystemApi
1204     @RequiresPermission(Manifest.permission.MANAGE_USB)
getPorts()1205     public @NonNull List<UsbPort> getPorts() {
1206         if (mService == null) {
1207             return Collections.emptyList();
1208         }
1209 
1210         List<ParcelableUsbPort> parcelablePorts;
1211         try {
1212             parcelablePorts = mService.getPorts();
1213         } catch (RemoteException e) {
1214             throw e.rethrowFromSystemServer();
1215         }
1216 
1217         if (parcelablePorts == null) {
1218             return Collections.emptyList();
1219         } else {
1220             int numPorts = parcelablePorts.size();
1221 
1222             ArrayList<UsbPort> ports = new ArrayList<>(numPorts);
1223             for (int i = 0; i < numPorts; i++) {
1224                 ports.add(parcelablePorts.get(i).getUsbPort(this));
1225             }
1226 
1227             return ports;
1228         }
1229     }
1230 
1231     /**
1232      * Should only be called by {@link UsbPort#getStatus}.
1233      *
1234      * @hide
1235      */
getPortStatus(UsbPort port)1236     UsbPortStatus getPortStatus(UsbPort port) {
1237         try {
1238             return mService.getPortStatus(port.getId());
1239         } catch (RemoteException e) {
1240             throw e.rethrowFromSystemServer();
1241         }
1242     }
1243 
1244     /**
1245      * Should only be called by {@link UsbPort#setRoles}.
1246      *
1247      * @hide
1248      */
setPortRoles(UsbPort port, int powerRole, int dataRole)1249     void setPortRoles(UsbPort port, int powerRole, int dataRole) {
1250         Log.d(TAG, "setPortRoles Package:" + mContext.getPackageName());
1251         try {
1252             mService.setPortRoles(port.getId(), powerRole, dataRole);
1253         } catch (RemoteException e) {
1254             throw e.rethrowFromSystemServer();
1255         }
1256     }
1257 
1258     /**
1259      * Enables USB port contaminant detection algorithm.
1260      *
1261      * @hide
1262      */
1263     @RequiresPermission(Manifest.permission.MANAGE_USB)
enableContaminantDetection(@onNull UsbPort port, boolean enable)1264     void enableContaminantDetection(@NonNull UsbPort port, boolean enable) {
1265         try {
1266             mService.enableContaminantDetection(port.getId(), enable);
1267         } catch (RemoteException e) {
1268             throw e.rethrowFromSystemServer();
1269         }
1270     }
1271 
1272     /**
1273      * Sets the component that will handle USB device connection.
1274      * <p>
1275      * Setting component allows to specify external USB host manager to handle use cases, where
1276      * selection dialog for an activity that will handle USB device is undesirable.
1277      * Only system components can call this function, as it requires the MANAGE_USB permission.
1278      *
1279      * @param usbDeviceConnectionHandler The component to handle usb connections,
1280      * {@code null} to unset.
1281      *
1282      * {@hide}
1283      */
setUsbDeviceConnectionHandler(@ullable ComponentName usbDeviceConnectionHandler)1284     public void setUsbDeviceConnectionHandler(@Nullable ComponentName usbDeviceConnectionHandler) {
1285         try {
1286             mService.setUsbDeviceConnectionHandler(usbDeviceConnectionHandler);
1287         } catch (RemoteException e) {
1288             throw e.rethrowFromSystemServer();
1289         }
1290     }
1291 
1292     /**
1293      * Returns whether the given functions are valid inputs to UsbManager.
1294      * Currently the empty functions or any of MTP, PTP, RNDIS, MIDI, NCM are accepted.
1295      *
1296      * Only one function may be set at a time, except for RNDIS and NCM, which can be set together
1297      * because from a user perspective they are the same function (tethering).
1298      *
1299      * @return Whether the mask is settable.
1300      *
1301      * {@hide}
1302      */
areSettableFunctions(long functions)1303     public static boolean areSettableFunctions(long functions) {
1304         return functions == FUNCTION_NONE
1305                 || ((~SETTABLE_FUNCTIONS & functions) == 0
1306                         && ((Long.bitCount(functions) == 1)
1307                                 || (functions == (FUNCTION_RNDIS | FUNCTION_NCM))));
1308     }
1309 
1310     /**
1311      * Converts the given function mask to string. Maintains ordering with respect to init scripts.
1312      *
1313      * @return String representation of given mask
1314      *
1315      * {@hide}
1316      */
usbFunctionsToString(long functions)1317     public static String usbFunctionsToString(long functions) {
1318         StringJoiner joiner = new StringJoiner(",");
1319         if ((functions & FUNCTION_MTP) != 0) {
1320             joiner.add(UsbManager.USB_FUNCTION_MTP);
1321         }
1322         if ((functions & FUNCTION_PTP) != 0) {
1323             joiner.add(UsbManager.USB_FUNCTION_PTP);
1324         }
1325         if ((functions & FUNCTION_RNDIS) != 0) {
1326             joiner.add(UsbManager.USB_FUNCTION_RNDIS);
1327         }
1328         if ((functions & FUNCTION_MIDI) != 0) {
1329             joiner.add(UsbManager.USB_FUNCTION_MIDI);
1330         }
1331         if ((functions & FUNCTION_ACCESSORY) != 0) {
1332             joiner.add(UsbManager.USB_FUNCTION_ACCESSORY);
1333         }
1334         if ((functions & FUNCTION_AUDIO_SOURCE) != 0) {
1335             joiner.add(UsbManager.USB_FUNCTION_AUDIO_SOURCE);
1336         }
1337         if ((functions & FUNCTION_NCM) != 0) {
1338             joiner.add(UsbManager.USB_FUNCTION_NCM);
1339         }
1340         if ((functions & FUNCTION_ADB) != 0) {
1341             joiner.add(UsbManager.USB_FUNCTION_ADB);
1342         }
1343         return joiner.toString();
1344     }
1345 
1346     /**
1347      * Parses a string of usb functions that are comma separated.
1348      *
1349      * @return A mask of all valid functions in the string
1350      *
1351      * {@hide}
1352      */
usbFunctionsFromString(String functions)1353     public static long usbFunctionsFromString(String functions) {
1354         if (functions == null || functions.equals(USB_FUNCTION_NONE)) {
1355             return FUNCTION_NONE;
1356         }
1357         long ret = 0;
1358         for (String function : functions.split(",")) {
1359             if (FUNCTION_NAME_TO_CODE.containsKey(function)) {
1360                 ret |= FUNCTION_NAME_TO_CODE.get(function);
1361             } else if (function.length() > 0) {
1362                 throw new IllegalArgumentException("Invalid usb function " + functions);
1363             }
1364         }
1365         return ret;
1366     }
1367 
1368     /**
1369      * Converts the given integer of USB speed to corresponding bandwidth.
1370      *
1371      * @return a value of USB bandwidth
1372      *
1373      * {@hide}
1374      */
usbSpeedToBandwidth(int speed)1375     public static int usbSpeedToBandwidth(int speed) {
1376         switch (speed) {
1377             case UsbSpeed.USB4_GEN3_40Gb:
1378                 return USB_DATA_TRANSFER_RATE_40G;
1379             case UsbSpeed.USB4_GEN3_20Gb:
1380                 return USB_DATA_TRANSFER_RATE_20G;
1381             case UsbSpeed.USB4_GEN2_20Gb:
1382                 return USB_DATA_TRANSFER_RATE_20G;
1383             case UsbSpeed.USB4_GEN2_10Gb:
1384                 return USB_DATA_TRANSFER_RATE_10G;
1385             case UsbSpeed.SUPERSPEED_20Gb:
1386                 return USB_DATA_TRANSFER_RATE_20G;
1387             case UsbSpeed.SUPERSPEED_10Gb:
1388                 return USB_DATA_TRANSFER_RATE_10G;
1389             case UsbSpeed.SUPERSPEED:
1390                 return USB_DATA_TRANSFER_RATE_5G;
1391             case UsbSpeed.HIGHSPEED:
1392                 return USB_DATA_TRANSFER_RATE_HIGH_SPEED;
1393             case UsbSpeed.FULLSPEED:
1394                 return USB_DATA_TRANSFER_RATE_FULL_SPEED;
1395             case UsbSpeed.LOWSPEED:
1396                 return USB_DATA_TRANSFER_RATE_LOW_SPEED;
1397             default:
1398                 return USB_DATA_TRANSFER_RATE_UNKNOWN;
1399         }
1400     }
1401 
1402     /**
1403      * Converts the given usb gadgdet hal version to String
1404      *
1405      * @return String representation of Usb Gadget Hal Version
1406      *
1407      * {@hide}
1408      */
usbGadgetHalVersionToString(int version)1409     public static @NonNull String usbGadgetHalVersionToString(int version) {
1410         String halVersion;
1411 
1412         if (version == GADGET_HAL_V1_2) {
1413             halVersion = GADGET_HAL_VERSION_1_2;
1414         } else if (version == GADGET_HAL_V1_1) {
1415             halVersion = GADGET_HAL_VERSION_1_1;
1416         } else if (version == GADGET_HAL_V1_0) {
1417             halVersion = GADGET_HAL_VERSION_1_0;
1418         } else {
1419             halVersion = GADGET_HAL_UNKNOWN;
1420         }
1421 
1422         return halVersion;
1423     }
1424 }
1425