title: "java.lang.IllegalStateException: not connected to MediaScannerService" when adding a file to the media library in Android
body: <p>I'm receiving this <code>java.lang.IllegalStateException: not connected to MediaScannerService</code> exception in some crash reports from my app.</p>
  
  <p>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 <a href="https://stackoverflow.com/questions/9707572/android-how-to-get-and-setchange-id3-tagmetadata-of-audio-files/11035755#11035755">How to get and set (change) ID3 tag (metadata) of audio files?</a></p>
  
  <p>The method:</p>
  
  <pre><code>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", "-&gt; uri: " + uri, DEBUG_TAG);
              msc.disconnect();  
          }
          public void onMediaScannerConnected() {
              for (int i = 0; i &lt; file.length; i++) {
                  msc.scanFile(file[i].getAbsolutePath(), mime[i]);
              }
          }
      });
      msc.connect();
  }
  </code></pre>
  
  <p>My calls:</p>
  
  <pre><code>Utils.scanMedia(getApplicationContext(), 
                  new File[] {myVideo}, 
                  new String[] {"video/*"});
  </code></pre>
  
  <p>or</p>
  
  <pre><code>Utils.scanMedia(getApplicationContext(), 
                  new File[] {myOtherVideo, myAudio}, 
                  new String[] {"video/*", "audio/*"});`
  </code></pre>
  
  <p>How can avoid those exceptions?</p>