Tuesday, 3 April 2012

Wait for the SD Card availability


Sometimes you may have to load data from your SD Card. Unfortunately in some cases, the SD Card is not always  available.
Let's take for example a Live Wallpaper on which images are loaded from the SD Card. When you boot your device, the Live Wallpaper can be launched before the SD Card is mounted.
So what you have to do first is, check that the SD Card is present and if it's not the case, wait for it's availability.
Here is simple snippet that solves this issue:


//Check for the availability of the SD Card
if (!android.os.Environment.getExternalStorageState()                .equals(android.os.Environment.MEDIA_MOUNTED)) {    final IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);    filter.addDataScheme("file");    //Wait for the availability of the SD Card    registerReceiver(new BroadcastReceiver() {       @Override       public void onReceive(Context context, Intent intent) {          //Load the image          this.background = BitmapFactory.decodeStream(          new FileInputStream(backgroundPath));       }    }, new IntentFilter(filter)); } else {      //Load the image    this.background = BitmapFactory    .decodeStream(new FileInputStream(backgroundPath)); }

No comments:

Post a Comment