Bill Evans
Bill Evans

Reputation: 71

Can I "safely remove" a USB device from Android OTG, after writing files to it?

This regards Android Lollipop 5.0 and above only.

We have a custom device that can be mounted as a file system over USB. I've written an Android app that lets the user mount the device with OTG, after which we update files on the device. That part works like a charm (modulo how awful DocumentFile is). What I can't figure out is how to unmount or safely remove the device, or to let the user know that they can safely unplug it.

The best I've found is to start an Activity with the intent ACTION_MEMORY_CARD_SETTINGS. But that is a horrible user experience, visually, not to mention the likely non-compliance of typical users. (They'll just unplug when they see the Manage Storage page.)

Does anyone know a way to programmatically flush the writes to the USB device? Or to determine if there are still writes pending to a file, to a device, to anything? Or any way to safely remove an OTG USB device that doesn't stink?

(I gather that before Lollipop, when a mounted USB device was a real file system, with real Files, one could sync(), but that critical facility is apparently lost. If there's a way to get that back, I'd love to know it.)

Upvotes: 3

Views: 1973

Answers (1)

TomorrowPlusX
TomorrowPlusX

Reputation: 1215

While you can't call sync() on an external File as of Lollipop, I've found that I can get the ParcelFileDescriptor for the DocumentFile that the StorageAccessFramework gives you - then, you can get a file descriptor for it, and call sync() on it.

Specifically, to workaround this issue in my app I ended up writing code that walks my external storage directory and for each file opens a ParcelFileDescriptor in read mode, calls sync() on its file descriptor, and then closes the ParcelFileDescriptor.

It's completely awful, but since doing this I haven't lost any data when ejecting the USB OTG storage media.

Upvotes: 2

Related Questions