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);
    }
相关推荐
vocal2 小时前
【我的安卓第一课】Android 多线程与异步通信机制(1)
android
顾林海2 小时前
ViewModel 销毁时机详解
android·面试·android jetpack
恋猫de小郭3 小时前
Google I/O Extended :2025 Flutter 的现状与未来
android·前端·flutter
@Ryan Ding4 小时前
MySQL主从复制与读写分离概述
android·mysql·adb
移动开发者1号5 小时前
Android 同步屏障(SyncBarrier)深度解析与应用实战
android·kotlin
移动开发者1号5 小时前
深入协程调试:协程调试工具与实战
android·kotlin
雨白13 小时前
Jetpack系列(三):Room数据库——从增删改查到数据库平滑升级
android·android jetpack
花王江不语16 小时前
android studio 配置硬件加速 haxm
android·ide·android studio
江太翁18 小时前
mediapipe流水线分析 三
android·mediapipe
与火星的孩子对话18 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip