Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 4.0 定製:讓 USB Host 插入 HID 設備時彈出提示

編輯:關於 Android 程式設計

本文記錄在 Android 4.0 上定製的一項改動:當 USB Host 檢測到 HID 設備插入時,給出系統通知提示。原理部分網上資料很多,這裡直接進入改動點。

需要修改的文件

frameworks/base/services/java/com/android/server/usb/UsbService.java
frameworks/base/services/java/com/android/server/usb/UsbHostManager.java

第一步:讓 UsbHostManager 一定被創建

原代碼裡,UsbHostManager 的實例化被 pm.hasSystemFeature(FEATURE_USB_HOST) 條件包住。若設備的 feature 聲明不齊全,它就根本不會被創建,後續邏輯自然也不會執行。改法是把判斷去掉:

public UsbService(Context context) {
    mContext = context;
    mSettingsManager = new UsbSettingsManager(context);
    PackageManager pm = mContext.getPackageManager();
    // if (pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {  // modify by hclydao
    mHostManager = new UsbHostManager(context, mSettingsManager);
    // }
    if (new File("/sys/class/android_usb").exists()) {
        mDeviceManager = new UsbDeviceManager(context, mSettingsManager);
    }
}

第二步:在 UsbHostManager 中攔截插入事件

當硬件 USB Host 插入設備時會回調 usbDeviceAdded(),拔出時回調 usbDeviceRemoved()。

這裡有個關鍵發現:JNI 層回傳的 deviceClass 等字段全是 0,不能直接用。真正有效的信息藏在 int[] interfaceValues 裡——interfaceValues[1] 對應的就是 class:3 是 USB HID,8 是 Mass Storage,9 是 USB Hub。

於是在方法開頭加上判斷,命中 HID 就調用系統自帶的通知資源彈出提示,同時把設備名記錄下來,便於拔出時撤銷通知:

/* Called from JNI in monitorUsbHostBus() to report new USB devices */
private void usbDeviceAdded(String deviceName, int vendorID, int productID,
        int deviceClass, int deviceSubclass, int deviceProtocol,
        /* array of quintuples containing id, class, subclass, protocol
           and number of endpoints for each interface */
        int[] interfaceValues,
        /* array of quadruples containing address, attributes, max packet size
           and interval for each endpoint */
        int[] endpointValues) {

    // add by hclydao
    if ((interfaceValues != null) && (interfaceValues[1] == UsbConstants.USB_CLASS_HID)) {
        setUsbHostNotification(
                com.android.internal.R.string.usb_storage_notification_title,
                com.android.internal.R.string.usb_storage_notification_title,
                com.android.internal.R.drawable.stat_sys_tether_usb,
                true, true, null);
        if (dlist == null) dlist = new ArrayList<String>();
        dlist.add(deviceName);
    }

    if (isBlackListed(deviceName) || isBlackListed(deviceClass, deviceSubclass, deviceProtocol)) {
        return;
    }

    synchronized (mLock) {
        if (mDevices.get(deviceName) != null) {
            Slog.w(TAG, "device already on mDevices list: " + deviceName);
            return;
        }
        int numInterfaces = interfaceValues.length / 5;
        Parcelable[] interfaces = new UsbInterface[numInterfaces];
        try {
            // 把 interfaceValues 重新打包成 UsbInterface 數組
            int intf, endp, ival = 0, eval = 0;
            for (intf = 0; intf < numInterfaces; intf++) {
                int interfaceId = interfaceValues[ival++];
                int interfaceClass = interfaceValues[ival++];
                int interfaceSubclass = interfaceValues[ival++];
                int interfaceProtocol = interfaceValues[ival++];
                int numEndpoints = interfaceValues[ival++];
                Parcelable[] endpoints = new UsbEndpoint[numEndpoints];
                for (endp = 0; endp < numEndpoints; endp++) {
                    int address = endpointValues[eval++];
                    int attributes = endpointValues[eval++];
                    int maxPacketSize = endpointValues[eval++];
                    int interval = endpointValues[eval++];
                    endpoints[endp] = new UsbEndpoint(address, attributes, maxPacketSize, interval);
                }
                // 任一 interface 命中黑名單則整體拒絕
                if (isBlackListed(interfaceClass, interfaceSubclass, interfaceProtocol)) {
                    return;
                }
                interfaces[intf] = new UsbInterface(interfaceId, interfaceClass,
                        interfaceSubclass, interfaceProtocol, endpoints);
            }
        } catch (Exception e) {
            // 若設備未正確填寫 bNumEndpoints,可能出現下標越界
            Slog.e(TAG, "error parsing USB descriptors", e);
            return;
        }
        UsbDevice device = new UsbDevice(deviceName, vendorID, productID,
                deviceClass, deviceSubclass, deviceProtocol, interfaces);
        mDevices.put(deviceName, device);
        mSettingsManager.deviceAttached(device);
    }
}

第三步:拔出時撤銷通知

/* Called from JNI in monitorUsbHostBus to report USB device removal */
private void usbDeviceRemoved(String deviceName) {
    if (dlist != null) {
        for (int i = 0; i < dlist.size(); i++) {
            if (dlist.get(i).equals(deviceName)) {
                dlist.remove(i);
                // 最後一個設備拔出時才取消通知
                setUsbHostNotification(0, 0, 0, false, false, null);
                break;
            }
        }
    }
    synchronized (mLock) {
        UsbDevice device = mDevices.remove(deviceName);
        if (device != null) {
            mSettingsManager.deviceDetached(device);
        }
    }
}

第四步:通知本身的封裝

複用系統現成的通知資源即可,無需自建圖標與文案:

private synchronized void setUsbHostNotification(int titleId, int messageId, int icon,
        boolean visible, boolean dismissable, PendingIntent pi) {
    if (!visible && mUsbHostNotification == null) {
        return;
    }
    NotificationManager notificationManager = (NotificationManager)
            mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    if (notificationManager == null) {
        return;
    }
    if (mUsbHostNotification != null && visible) {
        // 即將復用,先撤銷上一條
        final int notificationId = mUsbHostNotification.icon;
        notificationManager.cancel(notificationId);
    }
    if (visible) {
        Resources r = Resources.getSystem();
        CharSequence title = r.getText(titleId);
        CharSequence message = r.getText(messageId);
        if (mUsbHostNotification == null) {
            mUsbHostNotification = new Notification();
            mUsbHostNotification.when = 0;
        }
        mUsbHostNotification.defaults &= ~Notification.DEFAULT_SOUND;
        if (dismissable) {
            mUsbHostNotification.flags = Notification.FLAG_AUTO_CANCEL;
        } else {
            mUsbHostNotification.flags = Notification.FLAG_ONGOING_EVENT;
        }
        mUsbHostNotification.tickerText = title;
        if (pi == null) {
            Intent intent = new Intent();
            pi = PendingIntent.getBroadcast(mContext, 0, intent, 0);
        }
        mUsbHostNotification.icon = icon;
        mUsbHostNotification.setLatestEventInfo(mContext, title, message, pi);
    }
    final int notificationId = mUsbHostNotification.icon;
    if (visible) {
        notificationManager.notify(notificationId, mUsbHostNotification);
    } else {
        notificationManager.cancel(notificationId);
    }
}

定製時的注意事項

第一,用 interfaceValues[1] 直接取 class 是依賴 JNI 數組布局的捷徑,寫法脆弱但有效,建議補上長度校驗避免越界。

第二,dlist 記錄的是設備名列表,多設備同時接入時,只有在最後一個設備拔出後才取消通知,這樣的判斷比「一拔就撤」更符合直覺。

第三,示例中 Notification.setLatestEventInfo() 在後續 Android 版本已被移除,若要把這套改動移植到 5.0 以上,必須改用 Notification.Builder 並配合 NotificationChannel,同時注意通知圖標需為白色透明的系統圖標。

第四,直接修改 framework 源碼需要重新編譯整個系統鏡像,升級維護成本高。若只是要區分不同設備類型並提示,更輕量的做法是在應用層通過 UsbManager 監聽 ACTION_USB_DEVICE_ATTACHED 廣播,讀取 UsbDevice 的接口類別來判斷。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved