1 package android.car.usb.handler;
2 
3 import android.content.BroadcastReceiver;
4 import android.content.Context;
5 import android.content.Intent;
6 import android.hardware.usb.UsbDevice;
7 import android.hardware.usb.UsbManager;
8 import android.os.UserHandle;
9 
10 import java.util.ArrayList;
11 import java.util.HashMap;
12 
13 /** Queues work to the BootUsbService job to scan for connected devices. */
14 public class BootUsbScanner extends BroadcastReceiver {
15 
16     @Override
onReceive(Context context, Intent intent)17     public void onReceive(Context context, Intent intent) {
18         // Only start the service if we are the system user. We cannot use the singleUser tag in the
19         // manifest for <receiver>s, so there is no way to avoid us registering this receiver as the
20         // non system user. Just return immediately if we are not.
21         if (context.getUserId() != UserHandle.USER_SYSTEM) {
22             return;
23         }
24         // we defer this processing to BootUsbService so that we are very quick to process
25         // LOCKED_BOOT_COMPLETED
26         UsbManager usbManager = context.getSystemService(UsbManager.class);
27         HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
28         if (deviceList.size() > 0) {
29             Intent bootUsbServiceIntent = new Intent(context, BootUsbService.class);
30             bootUsbServiceIntent.putParcelableArrayListExtra(
31                     BootUsbService.USB_DEVICE_LIST_KEY, new ArrayList<>(deviceList.values()));
32 
33             context.startForegroundService(bootUsbServiceIntent);
34         }
35     }
36 }
37