Taking a pic without the SD card

It seems like people seriously freak out when you want SD card access.  I’m not 100% sure what’s up with that, but I’ve seen a whole lot of 1 star reviews for nothing more than requesting SD card access.

Generally, the big thing we need SD card access for is taking pictures.  Most, if not all, of the examples online show using the SD card and sending an intent with the file path.  This works, but presents a few problems.  first of all, people freak out.  Not sure why, but they do.  Second, the SD card may not be mounted (or exist at all).  That’s obviously a problem.

Taking a local picture is problematic because the camera app won’t have access to your local file system to write files.  Its in a different process, with a different user.

To get around that, here’s a little trick I just got to work.  Will need to test on a wider set of phones, but it seems to work on my Galaxy Nexus.  I’m not sure if all of this is technically necessary, but it seems to work.  I will remove some parts and see when it breaks.

File file = null;
       try
       {
           FileOutputStream fout = c.openFileOutput(fileName, Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
           file = c.getFileStreamPath(fileName);
           fout.close();
       }
       catch (IOException e)
       {
           throw new RuntimeException(e);
       }
       return file;

What is the code doing?  This is just to create the file reference that you send with the image capture intent.  I’ll include the actual intent call later, but its pretty much all over the place and should be easy to find.

The key here is creating the file with permissions that allow the external app write to a file in your app directory.

This obviously must be creating an empty file with those permissions, or this wouldn’t work.  I haven’t checked the folder, though, but I assume that’s what its doing.

I am concerned that this won’t work on all devices or versions, just because its a little hacky, but this is pretty core Java/Linux file system stuff, so maybe we’ll get lucky.

Its possible older or custom versions of the camera app are sensitive to where files are stored.  YMMV.