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