Programmatically Turn Off USB Storage on Android Devices
Asked Answered
M

2

16

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?

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

Mayweed answered 13/9, 2011 at 4:18 Comment(2)
This can work if the phone is rooted and the current OS has got the required API permission accessKatharinekatharsis
Like Nikolay said below, unless you're only supporting pre-Honeycomb devices, it's not worth the effort to make a UMS toggling function. MTP, while many may not like it (myself included), does have its good points. For example, with MTP you can simultaneously delete files from your phone via your computer or from your device and see the changes reflected immediately in your computer and device. With UMS, you have to mount/dismount every time you need to switch usage between your device and your computer. So MTP offers you more flexibility.Smallclothes
R
4

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.

Raffaello answered 13/9, 2011 at 5:21 Comment(1)
Correct, you cannot mount or unmount USB, unless your application is part of the firmware.Curtsy
E
7

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:

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:

MountService.setUsbMassStorageEnabled(false);

or

StorageManager.disableUsbMassStorage();

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

Exaggerated answered 13/9, 2011 at 4:19 Comment(1)
so how to access those apis?Shotwell
R
4

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.

Raffaello answered 13/9, 2011 at 5:21 Comment(1)
Correct, you cannot mount or unmount USB, unless your application is part of the firmware.Curtsy

© 2022 - 2024 — McMap. All rights reserved.