編輯:關於 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 的實例化被 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);
}
}
當硬件 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 的接口類別來判斷。
Android Studio 如何修改快捷鍵
在 Android Studio 中,如果你嫌某個快捷鍵太複雜、想改一改,該怎麼辦呢?第一步得先找到它——但偏偏 Android Studio 搜索快捷鍵有個 bug:你
Android 意圖全解:顯式意圖、隱式意圖、意圖過濾器與組件間傳值
Intent 主要分為顯式意圖與隱式意圖兩類。顯式意圖通常用於啟動本應用內的 Activity 並在組件間傳遞數據;隱式意圖則常見於調用系統的某些特定動作(如打電話、發短
IntelliJ IDEA 與 Android Studio 上使用 Git 全流程圖文教程
由於 Android Studio 是基於 IntelliJ IDEA 開發而來的,所用的插件其實都源自 IDEA。IDEA 與 Android Studio 默認已經安
CoordinatorLayout.Behavior 自訂效果實作詳解
先看一張效果圖,要達成的目標便一目了然: 實作思路 1. 首先自訂一個 View,包含頭部與列表。 2. 為自訂 View 加上註解,也就是預設使用自訂的 Behav