am f3329452: Open file directly when external storage emulated.

* commit 'f3329452c5554f4a3bcd3c41d7ec669a0d55c997':
  Open file directly when external storage emulated.
diff --git a/src/com/android/providers/media/MediaProvider.java b/src/com/android/providers/media/MediaProvider.java
index 22b4158..b28af22 100644
--- a/src/com/android/providers/media/MediaProvider.java
+++ b/src/com/android/providers/media/MediaProvider.java
@@ -4841,6 +4841,29 @@
                     int volumeID = FileUtils.getFatVolumeId(path);
                     if (LOCAL_LOGV) Log.v(TAG, path + " volume ID: " + volumeID);
 
+                    // Must check for failure!
+                    // If the volume is not (yet) mounted, this will create a new
+                    // external-ffffffff.db database instead of the one we expect.  Then, if
+                    // android.process.media is later killed and respawned, the real external
+                    // database will be attached, containing stale records, or worse, be empty.
+                    if (volumeID == -1) {
+                        String state = Environment.getExternalStorageState();
+                        if (Environment.MEDIA_MOUNTED.equals(state) ||
+                                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
+                            // This may happen if external storage was _just_ mounted.  It may also
+                            // happen if the volume ID is _actually_ 0xffffffff, in which case it
+                            // must be changed since FileUtils::getFatVolumeId doesn't allow for
+                            // that.  It may also indicate that FileUtils::getFatVolumeId is broken
+                            // (missing ioctl), which is also impossible to disambiguate.
+                            Log.e(TAG, "Can't obtain external volume ID even though it's mounted.");
+                        } else {
+                            Log.i(TAG, "External volume is not (yet) mounted, cannot attach.");
+                        }
+
+                        throw new IllegalArgumentException("Can't obtain external volume ID for " +
+                                volume + " volume.");
+                    }
+
                     // generate database name based on volume ID
                     String dbName = "external-" + Integer.toHexString(volumeID) + ".db";
                     helper = new DatabaseHelper(context, dbName, false,