Debian Codegraph @

core/java/android/hardware/usb/UsbManager.java

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