Change ANDROID_ID for Instant Apps

ANDROID_ID for Instant Apps now has the following properties:
1) per-app scoped
2) reset if the user clears the Instant App
3) remains the same if the Instant App gets upgraded to an installed
app.

Note that if the user goes instant -> installed_1 -> uninstall ->
installed_2 the ANDROID_ID at installed_1 will not be the same as
installed_2. This was deemed better than the id changing on the upgrade
step.

Test: manual
Change-Id: I532975c50049c94ff80902a897e001dd35a69f9f
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 169a034..48429e8 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -1109,6 +1109,33 @@
         // Retrieve the ssaid from the table if present.
         final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
                 name);
+        // If the app is an Instant App use its stored SSAID instead of our own.
+        final String instantSsaid;
+        final long token = Binder.clearCallingIdentity();
+        try {
+            instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
+                    owningUserId);
+        } catch (RemoteException e) {
+            Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
+            return null;
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+        if (instantSsaid != null) {
+            // Use the stored value if it is still valid.
+            if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
+                return ssaid;
+            }
+            // The value has changed, update the stored value.
+            final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
+                    SETTINGS_TYPE_SSAID, owningUserId);
+            final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
+                    true, callingPkg.packageName);
+            if (!success) {
+                throw new IllegalStateException("Failed to update instant app android id");
+            }
+            return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId, name);
+        }
 
         // Lazy initialize ssaid if not yet present in ssaid table.
         if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {