代码中动态控制U盘挂载和卸载。(仅适用于系统应用)
反射方式实现。
需要添加android:sharedUserId="android.uid.system" 到AndroidManifest.xml
java
public static void mountDisk() {
Log.v(TAG, "mountDisk begin");
try {
Class<?> clz = Class.forName("android.os.ServiceManager");
Method getService = clz.getMethod("getService", String.class);
Object powerService = getService.invoke(null, "mount");
Class<?> cStub = Class.forName("android.os.storage.IStorageManager$Stub");
Method asInterface = cStub.getMethod("asInterface", IBinder.class);
Object IPowerManager = asInterface.invoke(null, powerService);
Method shutDown = IPowerManager.getClass().getMethod("mount", String.class);
shutDown.invoke(IPowerManager, "public:8,1");
} catch (Exception e) {
e.printStackTrace();
}
Log.v(TAG, "mountDisk end");
}
public static void unmountDisk() {
Log.v(TAG, "unmountDisk begin");
try {
Class<?> clz = Class.forName("android.os.ServiceManager");
Method getService = clz.getMethod("getService", String.class);
Object powerService = getService.invoke(null, "mount");
Class<?> cStub = Class.forName("android.os.storage.IStorageManager$Stub");
Method asInterface = cStub.getMethod("asInterface", IBinder.class);
Object IPowerManager = asInterface.invoke(null, powerService);
Method shutDown = IPowerManager.getClass().getMethod("unmount", String.class);
shutDown.invoke(IPowerManager, "public:8,1");
} catch (Exception e) {
e.printStackTrace();
}
Log.v(TAG, "unmountDisk end");
}
public static boolean isUsbDiskMounted() {
String mount = SystemPropertiesUtil.getProperty("vold.usbdisk.state", "");
return "mounted".equals(mount);
}