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);
    }
相关推荐
正经教主12 分钟前
【App开发】02:Android Studio项目环境设置
android·ide·android studio
全栈软件开发1 小时前
最新版T5友价互站网源码商城PHP源码交易平台 完整带手机版源码网系统源码
android·开发语言·php
shykevin1 小时前
uni-app x开发商城系统,小程序发布,h5发布,安卓打包
android·小程序·uni-app
且白1 小时前
uniapp接入安卓端极光推送离线打包
android·uni-app
在狂风暴雨中奔跑1 小时前
使用MediaRecorder+MediaProjection高效实现Android录屏
android
YoungP1 小时前
让人头疼的AndroidStudio、Gradle、AGP..
android
我命由我123452 小时前
Android WebView - loadUrl 方法的长度限制
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
Coffeeee2 小时前
面试被问到Compose的副作用不会,只怪我没好好学
android·kotlin·android jetpack
Greenland_123 小时前
Android Gralde补全计划 productFlavors多渠道打包(变体/多客户)
android
Just_Paranoid3 小时前
【TaskStackListener】Android 中用于监听和响应任务栈
android·ams·task·taskstack