Saving Media from an Android Application

Some applications allow users to save photos, movies or music on the device. In this article, we will explore some of the best practices in that area.

First, you need to decide where to save the file. In most cases, you should not save into an application private folder. These folders are removed when the application is uninstalled. Best place to save media files is in a public shared folder on external SD card storage. For example, the following code gets the public Pictures folder on the SD card.

File targetDir;

targetDir = Environment.getExternalStoragePublicDirectory(
//Create the folder if necessary
if (targetDir.exists() == false) {
File outFile = new File(targetDir, "photo.jpg");

On most devices, this will select the /mnt/sdcard/Pictures folder. Unlike the Context.getExternalFilesDir() method, getExternalStoragePublicDirectory() does not create the folder for you. That is why we need create it using mkdir().

To write to the SD card, you must seek the android.permission.WRITE_EXTERNAL_STORAGE permission. So, add this to AndroidManifest.xml.

<manifest …>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>


Writing to the file itself is easy. You use the usual Java IO for that. Only thing to keep in mind is that you should always work with the file system from a separate thread so that you don’t tie up the main GUI thread.

The gallery application of some devices do not scan the Pictures folder on the SD card. If that happens, users will not be able to view the saved file from the media gallery. We need to inform the media scanner about the new file.  Add this code to do that. This will make the gallery application aware of the newly saved file.

    new String[] { outFile.toString() }, null,
    new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s