"java.lang.IllegalStateException: not connected to MediaScannerService" when adding a file to the media library in Android

StackOverflow https://stackoverflow.com/questions/16477635

Question

I'm receiving this java.lang.IllegalStateException: not connected to MediaScannerService exception in some crash reports from my app.

They are not too many, but I don’t know what’s wrong in my code, because on my phone/emulator it works OK. I’m using a method to call the MediaScanner adapted from a SO question/answer at How to get and set (change) ID3 tag (metadata) of audio files?

The method:

public static void scanMedia(Context context, final File[] file, final String[] mime) {
    msc = new MediaScannerConnection(context, new MediaScannerConnectionClient() {
        public void onScanCompleted(String path, Uri uri) {
            Utils.logger("d", "Scanned " + path + ":", DEBUG_TAG);
            Utils.logger("d", "-> uri: " + uri, DEBUG_TAG);
            msc.disconnect();  
        }
        public void onMediaScannerConnected() {
            for (int i = 0; i < file.length; i++) {
                msc.scanFile(file[i].getAbsolutePath(), mime[i]);
            }
        }
    });
    msc.connect();
}

My calls:

Utils.scanMedia(getApplicationContext(), 
                new File[] {myVideo}, 
                new String[] {"video/*"});

or

Utils.scanMedia(getApplicationContext(), 
                new File[] {myOtherVideo, myAudio}, 
                new String[] {"video/*", "audio/*"});`

How can avoid those exceptions?

Was it helpful?

Solution

It's a race condition. You are iterating over multiple files in the onMediaScannerConnected() method. But you disconnect() the connection you use to add files.

Say you have three files. File one starts and for file two you can call scanFile() without any problems as well. But before you call scanFile() for the third file, the first one has already been completed. Thus Android calls your callback method onScanCompleted(). And here you are calling disconnect() thus closing the connection you want to use for the third file. Thus with the third scanFile()call the connection is no longer valid!

This might happen, or not. Depending on which thread runs how fast and gets processing time in which particular order. Thus you get this exceptions only every now and then.

I will provide a pull request with a fix for ytdownloader if you like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top