Align databases with migration lifecycle.

We've seen evidence of the remote caller attempting multiple
migrations, so adjust the logic to ensure that we always have a
valid database while an active migration is taking place.

Also protect the Mainline code from a legacy provided that is
having trouble with lifecycle events.

Bug: 151960212
Test: atest --test-mapping packages/providers/MediaProvider
Change-Id: I3920bb652352ca3a08d2004fb5e3e135cbc0ce82
diff --git a/apex/framework/java/android/provider/MediaStore.java b/apex/framework/java/android/provider/MediaStore.java
index ca32355..0c9cd1e 100644
--- a/apex/framework/java/android/provider/MediaStore.java
+++ b/apex/framework/java/android/provider/MediaStore.java
@@ -768,7 +768,11 @@
      */
     public static void startLegacyMigration(@NonNull ContentResolver resolver,
             @NonNull String volumeName) {
-        resolver.call(AUTHORITY_LEGACY, START_LEGACY_MIGRATION_CALL, volumeName, null);
+        try {
+            resolver.call(AUTHORITY_LEGACY, START_LEGACY_MIGRATION_CALL, volumeName, null);
+        } catch (Exception e) {
+            Log.wtf(TAG, "Failed to deliver legacy migration event", e);
+        }
     }
 
     /**
@@ -780,7 +784,11 @@
      */
     public static void finishLegacyMigration(@NonNull ContentResolver resolver,
             @NonNull String volumeName) {
-        resolver.call(AUTHORITY_LEGACY, FINISH_LEGACY_MIGRATION_CALL, volumeName, null);
+        try {
+            resolver.call(AUTHORITY_LEGACY, FINISH_LEGACY_MIGRATION_CALL, volumeName, null);
+        } catch (Exception e) {
+            Log.wtf(TAG, "Failed to deliver legacy migration event", e);
+        }
     }
 
     private static @NonNull PendingIntent createRequest(@NonNull ContentResolver resolver,
diff --git a/legacy/src/com/android/providers/media/LegacyMediaProvider.java b/legacy/src/com/android/providers/media/LegacyMediaProvider.java
index b79a955..488e72a 100644
--- a/legacy/src/com/android/providers/media/LegacyMediaProvider.java
+++ b/legacy/src/com/android/providers/media/LegacyMediaProvider.java
@@ -143,13 +143,11 @@
                 switch (volumeName) {
                     case MediaStore.VOLUME_INTERNAL: {
                         mInternalDatabase.close();
-                        mInternalDatabase = null;
                         getContext().deleteDatabase(INTERNAL_DATABASE_NAME);
                         break;
                     }
                     default: {
                         mExternalDatabase.close();
-                        mExternalDatabase = null;
                         getContext().deleteDatabase(EXTERNAL_DATABASE_NAME);
                         break;
                     }