Save Image in External Storage Asynchronously


Saving Image or other files in External Storage is a regular task for an Android Programmer. 

Important Key Notes:
  • Add the relevant permissions to your AndroidManifest.xml file: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
  • A different thread should be used, because saving image or any other file is a time consuming task.  Otherwise you may get ANR error. Here, I have used Async Task.

At first check the external storage whether it is readable and writable

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // Can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
else {
        // Can't read or write
        mExternalStorageAvailable = mExternalStorageWriteable = false;
}
   
Log.i(TAG,"External Media: readable=" + mExternalStorageAvailable
            + " writable=" + mExternalStorageWriteable);


Write the image to disk in a random fashion 

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/com_mycompany_applicationname");    
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete (); 
try {
          FileOutputStream out = new FileOutputStream(file);
          out.flush();
          out.close();

catch (Exception e) {
          e.printStackTrace();
}



The whole at a glance 

private class SaveWallpaperAsyncTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {

String URL = "path/of/remote/image";
Log.i("SaveWallpaperAsyncTask","SinglePageImageURL = "+URL);

checkExternalMedia();
saveWallpaper(URL);

 return "Executed";
}      

@Override
protected void onPostExecute(String result) {
}

@Override
protected void onPreExecute() {
}

@Override
protected void onProgressUpdate(Void... values) {
}
        
private void saveWallpaper(String urlString) {
   Log.i("SaveWallpaperAsyncTask","Entered at saveWallpaper method");
   String root = Environment.getExternalStorageDirectory().toString();
   File myDir = new File(root + "/saved_images");    
   myDir.mkdirs();
   Random generator = new Random();
   int n = 10000;
   n = generator.nextInt(n);
   String fname = "Image-"+ n +".jpg";
   File file = new File (myDir, fname);
   if (file.exists ()) file.delete (); 

   try {
   FileOutputStream out = new FileOutputStream(file);
   out.flush();
   out.close();

   } catch (Exception e) {
   e.printStackTrace();
   }
   }

   private void checkExternalMedia() {
   boolean mExternalStorageAvailable = false;
   boolean mExternalStorageWriteable = false;
   String state = Environment.getExternalStorageState();

   if (Environment.MEDIA_MOUNTED.equals(state)) {
   // Can read and write the media
   mExternalStorageAvailable = mExternalStorageWriteable = true;
   } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
   // Can only read the media
   mExternalStorageAvailable = true;
   mExternalStorageWriteable = false;
   } else {
   // Can't read or write
   mExternalStorageAvailable = mExternalStorageWriteable = false;
   }
   
   Log.i(TAG,"External Media: readable=" + mExternalStorageAvailable
            + " writable=" + mExternalStorageWriteable);
   }

}

Set Remote Image as Wallpaper Asynchronously


In this post, you would learn how to Set Remote Image as Wallpaper Asynchronously. 

Important Key Notes: 
  • To use WallpaperManager, minimum API level have to be set to 5.
  • Add the relevant permissions to your AndroidManifest.xml file: <uses-permission android:name="android.permission.SET_WALLPAPER">
  • A different thread should be used, because setting wallpaper is a time consuming task.  Otherwise you may get ANR error. Here, I have used Async Task.

private class SetWallpaperAsyncTask extends AsyncTask<String, Void, String> {
   
   @Override
   protected String doInBackground(String... params) {
   String URL = "path/of/remote/image";
   setWallpaper(URL);
   return "Executed";
   }      

   @Override
   protected void onPostExecute(String result) {
   }

   @Override
   protected void onPreExecute() {
   }

   @Override
   protected void onProgressUpdate(Void... values) {
   }
        
   private void setWallpaper(String url) {
   try {
      WallpaperManager wpm = WallpaperManager.getInstance(ActivitySinglePage.this);
      InputStream ins = new URL(url).openStream();
      wpm.setStream(ins);
      } catch (Exception e) {
      e.printStackTrace();
      }
  }
}


Then call from where you need
new SetWallpaperAsyncTask().execute("");