开发者

Android SDCard mounting delay

I have an activity in my application which is basically a gallery which displays the pictures located on my sdcard. I am using this function to remount the sdcard to scan for new images when the activity starts:

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));    

The thing is when i do this the gallery does not show the updated images as android takes time to scan. So I put a sleep after that to wait for the scan to finish like this:

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));    

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

This开发者_如何学Python works but makes the application pause for 2 seconds. Is there a better way to handle this by putting a loading dialog? I'm not sure how to identify when the sdcard scan has been completed so that I can resume the activity.


This is definitely a bad approach to take. First, Thread.sleep() is something that should generally be avoided. Second, there is no way be assured that the scan has finished (what if there are a LOT of pictures or a slow device?).

The better way is to do this asynchronously. You can set up a BroadcastReciever to listen for Intent.ACTION_MEDIA_SCANNER_FINISHED. This intent will contain the directory you provided earlier back as the data field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜