java 以编程方式关闭 Android 设备上的 USB 存储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7396757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:46:46  来源:igfitidea点击:

Programmatically Turn Off USB Storage on Android Devices

javaandroidusb-mass-storage

提问by speedplane

On many android devices, when the device is plugged into the USB port of a computer or even on some USB charging devices, the phone goes into USB Storage mode. When the device is in this mode, android apps cannot access the sdcard. Is there any way (1) to detect when the device is in this mode and (2) to programmatically turn off USB storage, at least temporarily, so my android app can access the sdcard?

在许多安卓设备上,当设备插入计算机的 USB 端口甚至某些 USB 充电设备时,手机会进入 USB 存储模式。当设备处于此模式时,android 应用程序无法访问 sdcard。有没有办法 (1) 检测设备何时处于此模式和 (2) 以编程方式关闭 USB 存储,至少暂时关闭,以便我的 android 应用程序可以访问 SD 卡?

I've seen other SO questions and the answers are not really sufficient (e.g., Android: Detecting USB).

我看过其他 SO 问题,但答案并不足够(例如,Android: Detecting USB)。

采纳答案by Nikolay Elenkov

You can detect it (you have the link), but, AFAIK, you can't mount/unmount USB storage at least not with the public SDK APIs. In Honeycomb (3.0 and above), USB mass storage is no longer used to access the device's external storage, so your app and a computer can access it simultaneously.

您可以检测到它(您有链接),但是,AFAIK,您至少不能使用公共 SDK API 挂载/卸载 USB 存储。在 Honeycomb(3.0 及以上)中,USB 大容量存储不再用于访问设备的外部存储,因此您的应用程序和计算机可以同时访问它。

回答by tonykwok

A1: If current state of Sd card is SHARED it means that it has connected to PC in MSC mode, you can check this case as following:

A1: 如果 Sd 卡当前状态是 SHARED 表示它已经以 MSC 模式连接到 PC,您可以按以下方式检查这种情况:

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_SHARED.equals(state)) {
    // Sd card has connected to PC in MSC mode
}

A2: You can force to turn off usb mass storage connection by calling:

A2:您可以通过调用强制关闭 USB 大容量存储连接:

MountService.setUsbMassStorageEnabled(false);

or

或者

StorageManager.disableUsbMassStorage();

but unfortunately, both these API are not public accessible?!

但不幸的是,这两个 API 都不能公开访问?!

回答by user1699512

It blocks mass storage by using reflection on storageManger api . Storage Manager api is avaliable from sdk level -9.

它通过在 storageManger api 上使用反射来阻止大容量存储。存储管理器 API 可从 sdk 级别 -9 获得。

I am not able to reflect Mountservice api which can target less os level. If any one has done it please give suggestions

我无法反映可以针对较少操作系统级别的 Mountservice api。如果有人做过,请提供建议