Android 连接USB默认选中MTP模式
- 需求分析
Android系统默认连接USB会显示:正在通过USB为此设备充电,并且无法在电脑查看存储内容。需要实现的效果:Android 连接USB默认选中MTP模式,连接USB显示:正在通过USB传输文件,选择USB的使用方式的弹框下MTP模式为选中状态,并且可以在电脑端可以访问和写入存储空间。
- 解决方案
diff --git a/frameworks/base/services/usb/java/com/android/server/usb/UsbDeviceManager.java b/frameworks/base/services/usb/java/com/android/server/usb/UsbDeviceManager.java
index 59f7707..6a3d4d8 100755
--- a/frameworks/base/services/usb/java/com/android/server/usb/UsbDeviceManager.java
+++ b/frameworks/base/services/usb/java/com/android/server/usb/UsbDeviceManager.java
@@ -152,6 +152,8 @@ public class UsbDeviceManager {
private final UsbAlsaManager mUsbAlsaManager;
private Intent mBroadcastedIntent;
+ private UsbManager mUsbManager;
+
private class AdbSettingsObserver extends ContentObserver {
public AdbSettingsObserver() {
super(null);
@@ -732,7 +734,10 @@ public class UsbDeviceManager {
updateCurrentAccessory();
} else if (!mConnected) {
// restore defaults when USB is disconnected
- setEnabledFunctions(null, false);
+ //setEnabledFunctions(null, false);
+ mUsbManager = mContext.getSystemService(UsbManager.class);
+ mUsbManager.setCurrentFunction(UsbManager.USB_FUNCTION_MTP);
+ mUsbManager.setUsbDataUnlocked(true);
}
if (mBootCompleted) {
updateUsbStateBroadcastIfNeeded();
@@ -771,6 +776,9 @@ public class UsbDeviceManager {
break;
case MSG_BOOT_COMPLETED:
mBootCompleted = true;
+ mUsbManager = mContext.getSystemService(UsbManager.class);
+ mUsbManager.setCurrentFunction(UsbManager.USB_FUNCTION_MTP);
+ mUsbManager.setUsbDataUnlocked(true);
if (mCurrentAccessory != null) {
getCurrentSettings().accessoryAttached(mCurrentAccessory);
}
该方案实现:插拔的时候一直是默认MTP模式,并且在关机状态下连接USB,再重新开机仍然是MTP模式。在Android 7上测试没问题,其他系统可参考,修改UsbDeviceManager.java应该都是通用的。
- 尝试过的失败方案
修改均无效,连接USB仍然显示:正在通过USB为此设备充电,可在电脑端识别到设备,打开后不可访问文件系统。
<1>device/qcom/msm8953_64/msm8953_64.mk
ADDITIONAL_DEFAULT_PROPERTIES += persist.sys.usb.config=MTP
或 PRODUCT_PROPERTY_OVERRIDES += persist.sys.usb.config=MTP
<2>device/qcom/msm8953_64/system.prop
persist.sys.usb.config=mtp