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);
    }
相关推荐
auxor4 小时前
Android 开机动画音频播放优化方案
android
whysqwhw4 小时前
安卓实现屏幕共享
android
深盾科技4 小时前
Kotlin Data Classes 快速上手
android·开发语言·kotlin
一条上岸小咸鱼5 小时前
Kotlin 基本数据类型(五):Array
android·前端·kotlin
whysqwhw5 小时前
Room&Paging
android
whysqwhw5 小时前
RecyclerView超长列表优化
android
Tiger_Hu5 小时前
Android系统日历探索
android
whysqwhw5 小时前
RecyclerView卡顿
android
whysqwhw5 小时前
RecyclerView 与 ListView 在性能优化方面
android
檀越剑指大厂8 小时前
容器化 Android 开发效率:cpolar 内网穿透服务优化远程协作流程
android