Fix a bug where after the client calls startConsentActivity(), the framework is not loading the test activity as expected. Add permission to shell for cts test.

Test: end-to-end test with dev aiai and wellbeing apks
Bug: 218708840
Change-Id: Ia1c6a3575d85df274b4e6fcbed4881e576fcbfac
Ignore-AOSP-First: to prevent new feature leak.
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index d731180..be14e69 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -3699,6 +3699,9 @@
   <java-symbol type="string" name="config_defaultSystemCaptionsService" />
   <java-symbol type="string" name="config_defaultSystemCaptionsManagerService" />
   <java-symbol type="string" name="config_defaultAmbientContextDetectionService" />
+  <java-symbol type="string" name="config_defaultAmbientContextConsentComponent" />
+  <java-symbol type="string" name="config_ambientContextPackageNameExtraKey" />
+  <java-symbol type="string" name="config_ambientContextEventArrayExtraKey" />
   <java-symbol type="string" name="config_retailDemoPackage" />
   <java-symbol type="string" name="config_retailDemoPackageSignature" />
 
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index e9f940a..741fe4f 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -603,6 +603,9 @@
     <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
     <uses-permission android:name="android.permission.MODIFY_AUDIO_ROUTING" />
 
+    <!-- Permission required for CTS test - CtsAmbientContextDetectionServiceDeviceTest -->
+    <uses-permission android:name="android.permission.ACCESS_AMBIENT_CONTEXT_EVENT" />
+
     <!-- Permission required for CTS test - CallAudioInterceptionTest -->
     <uses-permission android:name="android.permission.CALL_AUDIO_INTERCEPTION" />
 
diff --git a/services/core/java/com/android/server/ambientcontext/AmbientContextManagerPerUserService.java b/services/core/java/com/android/server/ambientcontext/AmbientContextManagerPerUserService.java
index ab4d856..b73cf5b 100644
--- a/services/core/java/com/android/server/ambientcontext/AmbientContextManagerPerUserService.java
+++ b/services/core/java/com/android/server/ambientcontext/AmbientContextManagerPerUserService.java
@@ -29,6 +29,7 @@
 import android.app.ambientcontext.AmbientContextEvent;
 import android.app.ambientcontext.AmbientContextEventRequest;
 import android.app.ambientcontext.AmbientContextManager;
+import android.content.ActivityNotFoundException;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -39,7 +40,6 @@
 import android.os.Bundle;
 import android.os.RemoteCallback;
 import android.os.RemoteException;
-import android.provider.Settings;
 import android.service.ambientcontext.AmbientContextDetectionResult;
 import android.service.ambientcontext.AmbientContextDetectionServiceStatus;
 import android.text.TextUtils;
@@ -289,7 +289,7 @@
             return;
         }
 
-        if ((recentTasks != null) || recentTasks.getList().isEmpty()) {
+        if ((recentTasks == null) || recentTasks.getList().isEmpty()) {
             Slog.e(TAG, "Recent task list is empty!");
             return;
         }
@@ -297,40 +297,48 @@
         task = recentTasks.getList().get(0);
         if (!callingPackage.equals(task.topActivityInfo.packageName)) {
             Slog.e(TAG, "Recent task package name: " + task.topActivityInfo.packageName
-                    + " doesn't match with camera client package name: " + callingPackage);
+                    + " doesn't match with client package name: " + callingPackage);
             return;
         }
 
         // Start activity as the same task from the callingPackage
-        Intent intent = new Intent();
         ComponentName consentComponent = getConsentComponent();
-        if (consentComponent != null) {
-            Slog.e(TAG, "Starting consent activity for " + callingPackage);
-            Context context = getContext();
-            String packageNameExtraKey = Settings.Secure.getStringForUser(
-                    context.getContentResolver(),
-                    Settings.Secure.AMBIENT_CONTEXT_PACKAGE_NAME_EXTRA_KEY,
-                    userId);
-            String eventArrayExtraKey = Settings.Secure.getStringForUser(
-                    context.getContentResolver(),
-                    Settings.Secure.AMBIENT_CONTEXT_EVENT_ARRAY_EXTRA_KEY,
-                    userId);
+        if (consentComponent == null) {
+            Slog.e(TAG, "Consent component not found!");
+            return;
+        }
 
-            // Create consent activity intent with the calling package name and requested events.
+        Slog.d(TAG, "Starting consent activity for " + callingPackage);
+        Intent intent = new Intent();
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            Context context = getContext();
+            String packageNameExtraKey = context.getResources().getString(
+                    com.android.internal.R.string.config_ambientContextPackageNameExtraKey);
+            String eventArrayExtraKey = context.getResources().getString(
+                    com.android.internal.R.string.config_ambientContextEventArrayExtraKey);
+
+            // Create consent activity intent with the calling package name and requested events
             intent.setComponent(consentComponent);
             if (packageNameExtraKey != null) {
                 intent.putExtra(packageNameExtraKey, callingPackage);
+            } else {
+                Slog.d(TAG, "Missing packageNameExtraKey for consent activity");
             }
             if (eventArrayExtraKey != null) {
                 intent.putExtra(eventArrayExtraKey, eventTypes);
+            } else {
+                Slog.d(TAG, "Missing eventArrayExtraKey for consent activity");
             }
 
             // Set parent to the calling app's task
             ActivityOptions options = ActivityOptions.makeBasic();
             options.setLaunchTaskId(task.taskId);
-            context.startActivity(intent, options.toBundle());
-        } else {
-            Slog.e(TAG, "Consent component not found!");
+            context.startActivityAsUser(intent, options.toBundle(), context.getUser());
+        } catch (ActivityNotFoundException e) {
+            Slog.e(TAG, "unable to start consent activity");
+        } finally {
+            Binder.restoreCallingIdentity(identity);
         }
     }
 
@@ -339,13 +347,12 @@
      */
     private ComponentName getConsentComponent() {
         Context context = getContext();
-        String consentComponent = Settings.Secure.getStringForUser(
-                context.getContentResolver(),
-                Settings.Secure.AMBIENT_CONTEXT_CONSENT_COMPONENT,
-                getUserId());
+        String consentComponent = context.getResources().getString(
+                    com.android.internal.R.string.config_defaultAmbientContextConsentComponent);
         if (TextUtils.isEmpty(consentComponent)) {
             return null;
         }
+        Slog.i(TAG, "Consent component name: " + consentComponent);
         return ComponentName.unflattenFromString(consentComponent);
     }