Android通过反射动态挂载/卸载U盘

代码中动态控制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);
    }
相关推荐
simplepeng6 小时前
我们都知道但总是忽略的5个Jetpack Compose细节
android·android jetpack
刮风那天6 小时前
Android 如何提高进程优先级避免被查杀?
android
修行者对6668 小时前
安卓阿里云镜像
android
刮风那天8 小时前
Android AMS创建进程不用Binder而用Socket?
android·java·binder
知行合一。。。10 小时前
Python--05--面向对象(继承,多态)
android·开发语言·python
张小潇11 小时前
AOSP15 WMS/AMS系统开发 -窗口动画源码分析
android
程序员陆业聪13 小时前
Shadow核心原理:壳子Activity与代理机制的精妙设计
android
plainGeekDev13 小时前
Android 开发者再不转Kotlin,真的来不及了
android·kotlin
赏金术士13 小时前
第五章:数据层—网络请求与Repository
android·kotlin·compose
初雪云13 小时前
让安卓发版再简单一点,体验一键自动化发布
android·运维·自动化