Is it possible to Turn Off USB Storage on Android Devices programatically?

1.7k views Asked by At

I have tried to search over and over and got confused whether we can have control over USB storage without rooting the phone,if yes than how? I have tried the following method to enable and disable the permission but all in vain:

StorageManager storage = (StorageManager)getApplicationContext().getSystemService(STORAGE_SERVICE);
 Method method = storage.getClass().getDeclaredMethod("enableUsbMassStorage");
 method.setAccessible(true); 
 Object r = method.invoke(storage);

//And to disble mass storage:

StorageManager storage = (StorageManager) getApplicationContext().getSystemService(STORAGE_SERVICE);
Method method = storage.getClass().getDeclaredMethod("disableUsbMassStorage");
method.setAccessible(true);
Object r = method.invoke(storage);

If anyone has any idea about this please do share your knowledge.

Thanks in advance.

2

There are 2 answers

0
Yash Sampat On BEST ANSWER

The short answer to your question is NO. You cannot play around with the USB mass storage permission programmatically. You also wont find any Android apps that can do this reliably for any/all phones.

By default, the Android framework does not allow third-party applications to programmatically bypass the USB storage permissions. That choice is always left to the user, and that is the correct approach. Just think about it: if it were permitted, any third-party app could misuse that permission and transfer data over the USB connection.

The approach you have tried to use assumes that we know the names of the relevant methods and call them through reflection. This will work for certain OEMs' that have modified the base framework and exposed the relevant API calls. But it assumes that you know the names of those methods, and it will only work on a tiny subset of the vast number of Android phone models out there. It won't work on most phones, and it certainly wont work on any of the Nexus devices that have the original Android OS source code.

That is all.

1
Rajan Bhavsar On

If currently your 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
}

Now 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?!