Programmatically mounting USB storage on android 4.2.1

user1762148 picture user1762148 · May 1, 2013 · Viewed 7.7k times · Source

I've search and searched here, and no topics come close to answering the question.

Mounting and unmounting a USB stick from within a rooted APK. I've been successful in doing it from the command line via adb as follows:

prompt>> mount -t vfat -o rw /dev/block/sda1 /sdcard/usb

After this command, I can "cd /sdcard/usb" and can see the contents of the USB stick.

If I try this in code using the Process class, I can't see anything there from the command line in adb, a file explorer on the device, etc:

proc = Runtime.getRuntime().exec(new String[]{"/system/xbin/su", "-c", "mount -t vfat -o rw /dev/block/sdb1 /sdcard/usb"});

proc.waitFor();

This is a sandbox problem. It's driving me nuts. Here's what I think is going on, and I have no idea how to solve it: When the Process class invokes su, it does so in a completely new userspace -- it's own sandbox. The mount succeeds (I can see that from some debugging), then the process dies and returns to the app, which is in a different sandbox. Because of that, not only can I not see the mount, it unmounted with the su process going away.

I need to be able to mount a USB stick from my application, read/write to a file, then unmount it before it is removed (otherwise risk data corruption).

I've looked and looked for an android or java interface to the Linux mount(2) and umount(2) commands and have come up empty. There must be some way to do this!!

Answer

ibrahim picture ibrahim · Feb 6, 2014

you must read that carefully. mounting and unmounting should be done using that http://developer.android.com/guide/topics/connectivity/usb/host.html