Java – Is it possible to programmatically turn off USB storage on an Android device?

Is it possible to programmatically turn off USB storage on an Android device?… here is a solution to the problem.

Is it possible to programmatically turn off USB storage on an Android device?

I’ve tried searching over and over again, but am confused if we can control the USB storage without rooting the phone, and if so, how? I tried the following methods to enable and disable permissions, but it was 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 ideas about this, please share your knowledge.

Thanks in advance.

Solution

The short answer to your question is no. You cannot programmatically use USB mass storage permissions. You also won’t find any Android app that can reliably do this for any/all phones.

By default, the Android framework does not allow third-party applications to programmatically bypass USB storage permissions. This choice is always left to the user, which is the right approach. Think about it: if allowed, any third-party application could abuse that permission and transfer data over a USB connection.

The method you are trying to use assumes that we know the names of the methods in question and call them through reflection. This applies to some OEMs that modify the base framework and expose related API calls. But it assumes that you know the names of these methods, and that it only works with a small fraction of the large number of Android phone models that exist. It won’t work on most phones, and certainly not on any Nexus device with the source code of the original Android operating system.

That’s it.

Related Problems and Solutions