Merge "Don't use save/restore which stop drawing toggle switch drawables" into main
diff --git a/AconfigFlags.bp b/AconfigFlags.bp
index 1c6df75..7e6c30f 100644
--- a/AconfigFlags.bp
+++ b/AconfigFlags.bp
@@ -54,6 +54,7 @@
":android.service.controls.flags-aconfig-java{.generated_srcjars}",
":android.service.dreams.flags-aconfig-java{.generated_srcjars}",
":android.service.notification.flags-aconfig-java{.generated_srcjars}",
+ ":android.service.appprediction.flags-aconfig-java{.generated_srcjars}",
":android.service.voice.flags-aconfig-java{.generated_srcjars}",
":android.speech.flags-aconfig-java{.generated_srcjars}",
":android.systemserver.flags-aconfig-java{.generated_srcjars}",
@@ -125,6 +126,7 @@
"android.provider.flags-aconfig",
"android.security.flags-aconfig",
"android.server.app.flags-aconfig",
+ "android.service.appprediction.flags-aconfig",
"android.service.autofill.flags-aconfig",
"android.service.chooser.flags-aconfig",
"android.service.controls.flags-aconfig",
@@ -726,6 +728,19 @@
defaults: ["framework-minus-apex-aconfig-java-defaults"],
}
+// App prediction
+aconfig_declarations {
+ name: "android.service.appprediction.flags-aconfig",
+ package: "android.service.appprediction.flags",
+ srcs: ["core/java/android/service/appprediction/flags/*.aconfig"],
+}
+
+java_aconfig_library {
+ name: "android.service.appprediction.flags-aconfig-java",
+ aconfig_declarations: "android.service.appprediction.flags-aconfig",
+ defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
// Controls
aconfig_declarations {
name: "android.service.controls.flags-aconfig",
@@ -855,6 +870,13 @@
defaults: ["framework-minus-apex-aconfig-java-defaults"],
}
+java_aconfig_library {
+ name: "device_policy_aconfig_flags_lib_host",
+ aconfig_declarations: "device_policy_aconfig_flags",
+ host_supported: true,
+ defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
cc_aconfig_library {
name: "device_policy_aconfig_flags_c_lib",
aconfig_declarations: "device_policy_aconfig_flags",
diff --git a/OWNERS b/OWNERS
index 935b768..6bab92b 100644
--- a/OWNERS
+++ b/OWNERS
@@ -40,4 +40,6 @@
per-file PERFORMANCE_OWNERS = file:/PERFORMANCE_OWNERS
-per-file PACKAGE_MANAGER_OWNERS = file:/PACKAGE_MANAGER_OWNERS
\ No newline at end of file
+per-file PACKAGE_MANAGER_OWNERS = file:/PACKAGE_MANAGER_OWNERS
+
+per-file WEAR_OWNERS = file:/WEAR_OWNERS
diff --git a/Ravenwood.bp b/Ravenwood.bp
index d13c4d7..93febca4 100644
--- a/Ravenwood.bp
+++ b/Ravenwood.bp
@@ -33,6 +33,7 @@
"@$(location ravenwood/ravenwood-standard-options.txt) " +
"--debug-log $(location hoststubgen_framework-minus-apex.log) " +
+ "--stats-file $(location hoststubgen_framework-minus-apex_stats.csv) " +
"--out-impl-jar $(location ravenwood.jar) " +
@@ -56,6 +57,7 @@
"hoststubgen_dump.txt",
"hoststubgen_framework-minus-apex.log",
+ "hoststubgen_framework-minus-apex_stats.csv",
],
visibility: ["//visibility:private"],
}
diff --git a/WEAR_OWNERS b/WEAR_OWNERS
index 4127f99..da8c83e 100644
--- a/WEAR_OWNERS
+++ b/WEAR_OWNERS
@@ -10,3 +10,4 @@
rwmyers@google.com
nalmalki@google.com
shijianli@google.com
+latkin@google.com
diff --git a/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java b/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java
index 123b2ee..0fd2449 100644
--- a/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java
+++ b/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java
@@ -21,8 +21,11 @@
import static android.view.MotionEvent.ACTION_UP;
import static android.view.MotionEvent.TOOL_TYPE_FINGER;
import static android.view.MotionEvent.TOOL_TYPE_STYLUS;
+import static android.view.inputmethod.Flags.initiationWithoutInputConnection;
+import static org.junit.Assume.assumeFalse;
+
import android.app.Instrumentation;
import android.content.Context;
import android.perftests.utils.BenchmarkState;
@@ -186,6 +189,7 @@
@Test
public void onInputConnectionCreated() {
+ assumeFalse(initiationWithoutInputConnection());
final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
final View view = new View(mContext);
final EditorInfo editorInfo = new EditorInfo();
@@ -199,6 +203,7 @@
@Test
public void onInputConnectionClosed() {
+ assumeFalse(initiationWithoutInputConnection());
final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
final View view = new View(mContext);
while (state.keepRunning()) {
diff --git a/apex/jobscheduler/framework/java/android/app/job/JobInfo.java b/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
index 7284f47..7de6799 100644
--- a/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
+++ b/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
@@ -2354,9 +2354,9 @@
if (maxExecutionDelayMillis - windowStart < MIN_ALLOWED_TIME_WINDOW_MILLIS) {
if (enforceMinimumTimeWindows
&& Flags.enforceMinimumTimeWindows()) {
- throw new IllegalArgumentException("Jobs with a deadline and"
- + " functional constraints cannot have a time window less than "
- + MIN_ALLOWED_TIME_WINDOW_MILLIS + " ms."
+ throw new IllegalArgumentException("Time window too short. Constraints"
+ + " unlikely to be satisfied. Increase deadline to a reasonable"
+ + " duration."
+ " Job '" + service.flattenToShortString() + "#" + jobId + "'"
+ " has delay=" + windowStart
+ ", deadline=" + maxExecutionDelayMillis);
diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java
index 6883d18..aec464d 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java
@@ -241,6 +241,8 @@
private static final long MAX_TIME_WINDOW_MS = 24 * HOUR_IN_MILLIS;
private final JobScoreBucket[] mScoreBuckets = new JobScoreBucket[NUM_SCORE_BUCKETS];
private int mScoreBucketIndex = 0;
+ private long mCachedScoreExpirationTimeElapsed;
+ private int mCachedScore;
public void addScore(int add, long nowElapsed) {
JobScoreBucket bucket = mScoreBuckets[mScoreBucketIndex];
@@ -248,10 +250,17 @@
bucket = new JobScoreBucket();
bucket.startTimeElapsed = nowElapsed;
mScoreBuckets[mScoreBucketIndex] = bucket;
+ // Brand new bucket, there's nothing to remove from the score,
+ // so just update the expiration time if needed.
+ mCachedScoreExpirationTimeElapsed = Math.min(mCachedScoreExpirationTimeElapsed,
+ nowElapsed + MAX_TIME_WINDOW_MS);
} else if (bucket.startTimeElapsed < nowElapsed - MAX_TIME_WINDOW_MS) {
// The bucket is too old.
bucket.reset();
bucket.startTimeElapsed = nowElapsed;
+ // Force a recalculation of the cached score instead of just updating the cached
+ // value and time in case there are multiple stale buckets.
+ mCachedScoreExpirationTimeElapsed = nowElapsed;
} else if (bucket.startTimeElapsed
< nowElapsed - MAX_TIME_WINDOW_MS / NUM_SCORE_BUCKETS) {
// The current bucket's duration has completed. Move on to the next bucket.
@@ -261,16 +270,26 @@
}
bucket.score += add;
+ mCachedScore += add;
}
public int getScore(long nowElapsed) {
+ if (nowElapsed < mCachedScoreExpirationTimeElapsed) {
+ return mCachedScore;
+ }
int score = 0;
final long earliestElapsed = nowElapsed - MAX_TIME_WINDOW_MS;
+ long earliestValidBucketTimeElapsed = Long.MAX_VALUE;
for (JobScoreBucket bucket : mScoreBuckets) {
if (bucket != null && bucket.startTimeElapsed >= earliestElapsed) {
score += bucket.score;
+ if (earliestValidBucketTimeElapsed > bucket.startTimeElapsed) {
+ earliestValidBucketTimeElapsed = bucket.startTimeElapsed;
+ }
}
}
+ mCachedScore = score;
+ mCachedScoreExpirationTimeElapsed = earliestValidBucketTimeElapsed + MAX_TIME_WINDOW_MS;
return score;
}
@@ -378,10 +397,16 @@
@Override
public void prepareForExecutionLocked(JobStatus jobStatus) {
+ if (jobStatus.lastEvaluatedBias == JobInfo.BIAS_TOP_APP) {
+ // Don't include jobs for the TOP app in the score calculation.
+ return;
+ }
// Use the job's requested priority to determine its score since that is what the developer
// selected and it will be stable across job runs.
- final int score = mFallbackFlexibilityDeadlineScores
- .get(jobStatus.getJob().getPriority(), jobStatus.getJob().getPriority() / 100);
+ final int priority = jobStatus.getJob().getPriority();
+ final int score = mFallbackFlexibilityDeadlineScores.get(priority,
+ FcConfig.DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_SCORES
+ .get(priority, priority / 100));
JobScoreTracker jobScoreTracker =
mJobScoreTrackers.get(jobStatus.getSourceUid(), jobStatus.getSourcePackageName());
if (jobScoreTracker == null) {
@@ -394,6 +419,10 @@
@Override
public void unprepareFromExecutionLocked(JobStatus jobStatus) {
+ if (jobStatus.lastEvaluatedBias == JobInfo.BIAS_TOP_APP) {
+ // Jobs for the TOP app are excluded from the score calculation.
+ return;
+ }
// The job didn't actually start. Undo the score increase.
JobScoreTracker jobScoreTracker =
mJobScoreTrackers.get(jobStatus.getSourceUid(), jobStatus.getSourcePackageName());
@@ -401,8 +430,10 @@
Slog.e(TAG, "Unprepared a job that didn't result in a score change");
return;
}
- final int score = mFallbackFlexibilityDeadlineScores
- .get(jobStatus.getJob().getPriority(), jobStatus.getJob().getPriority() / 100);
+ final int priority = jobStatus.getJob().getPriority();
+ final int score = mFallbackFlexibilityDeadlineScores.get(priority,
+ FcConfig.DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_SCORES
+ .get(priority, priority / 100));
jobScoreTracker.addScore(-score, sElapsedRealtimeClock.millis());
}
@@ -649,21 +680,24 @@
(long) Math.scalb(mRescheduledJobDeadline, js.getNumPreviousAttempts() - 2),
mMaxRescheduledDeadline);
}
+
+ // Intentionally use the effective priority here. If a job's priority was effectively
+ // lowered, it will be less likely to run quickly given other policies in JobScheduler.
+ // Thus, there's no need to further delay the job based on flex policy.
+ final int jobPriority = js.getEffectivePriority();
+ final int jobScore =
+ getScoreLocked(js.getSourceUid(), js.getSourcePackageName(), nowElapsed);
+ // Set an upper limit on the fallback deadline so that the delay doesn't become extreme.
+ final long fallbackDurationMs = Math.min(3 * mFallbackFlexibilityDeadlineMs,
+ mFallbackFlexibilityDeadlines.get(jobPriority, mFallbackFlexibilityDeadlineMs)
+ + mFallbackFlexibilityAdditionalScoreTimeFactors
+ .get(jobPriority, MINUTE_IN_MILLIS) * jobScore);
+ final long fallbackDeadlineMs = earliest + fallbackDurationMs;
+
if (js.getLatestRunTimeElapsed() == JobStatus.NO_LATEST_RUNTIME) {
- // Intentionally use the effective priority here. If a job's priority was effectively
- // lowered, it will be less likely to run quickly given other policies in JobScheduler.
- // Thus, there's no need to further delay the job based on flex policy.
- final int jobPriority = js.getEffectivePriority();
- final int jobScore =
- getScoreLocked(js.getSourceUid(), js.getSourcePackageName(), nowElapsed);
- // Set an upper limit on the fallback deadline so that the delay doesn't become extreme.
- final long fallbackDeadlineMs = Math.min(3 * mFallbackFlexibilityDeadlineMs,
- mFallbackFlexibilityDeadlines.get(jobPriority, mFallbackFlexibilityDeadlineMs)
- + mFallbackFlexibilityAdditionalScoreTimeFactors
- .get(jobPriority, MINUTE_IN_MILLIS) * jobScore);
- return earliest + fallbackDeadlineMs;
+ return fallbackDeadlineMs;
}
- return js.getLatestRunTimeElapsed();
+ return Math.max(fallbackDeadlineMs, js.getLatestRunTimeElapsed());
}
@VisibleForTesting
@@ -976,7 +1010,8 @@
// Something has gone horribly wrong. This has only occurred on incorrectly
// configured tests, but add a check here for safety.
Slog.wtf(TAG, "Got invalid latest when scheduling alarm."
- + " Prefetch=" + js.getJob().isPrefetch());
+ + " prefetch=" + js.getJob().isPrefetch()
+ + " periodic=" + js.getJob().isPeriodic());
// Since things have gone wrong, the safest and most reliable thing to do is
// stop applying flex policy to the job.
mFlexibilityTracker.setNumDroppedFlexibleConstraints(js,
@@ -991,7 +1026,7 @@
if (DEBUG) {
Slog.d(TAG, "scheduleDropNumConstraintsAlarm: "
- + js.getSourcePackageName() + " " + js.getSourceUserId()
+ + js.toShortString()
+ " numApplied: " + js.getNumAppliedFlexibleConstraints()
+ " numRequired: " + js.getNumRequiredFlexibleConstraints()
+ " numSatisfied: " + Integer.bitCount(
@@ -1199,11 +1234,11 @@
DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_ADDITIONAL_SCORE_TIME_FACTORS
.put(PRIORITY_MAX, 0);
DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_ADDITIONAL_SCORE_TIME_FACTORS
- .put(PRIORITY_HIGH, 4 * MINUTE_IN_MILLIS);
+ .put(PRIORITY_HIGH, 3 * MINUTE_IN_MILLIS);
DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_ADDITIONAL_SCORE_TIME_FACTORS
- .put(PRIORITY_DEFAULT, 3 * MINUTE_IN_MILLIS);
+ .put(PRIORITY_DEFAULT, 2 * MINUTE_IN_MILLIS);
DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_ADDITIONAL_SCORE_TIME_FACTORS
- .put(PRIORITY_LOW, 2 * MINUTE_IN_MILLIS);
+ .put(PRIORITY_LOW, 1 * MINUTE_IN_MILLIS);
DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_ADDITIONAL_SCORE_TIME_FACTORS
.put(PRIORITY_MIN, 1 * MINUTE_IN_MILLIS);
DEFAULT_PERCENTS_TO_DROP_FLEXIBLE_CONSTRAINTS
@@ -1220,7 +1255,7 @@
private static final long DEFAULT_MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS = MINUTE_IN_MILLIS;
private static final long DEFAULT_RESCHEDULED_JOB_DEADLINE_MS = HOUR_IN_MILLIS;
- private static final long DEFAULT_MAX_RESCHEDULED_DEADLINE_MS = 5 * DAY_IN_MILLIS;
+ private static final long DEFAULT_MAX_RESCHEDULED_DEADLINE_MS = DAY_IN_MILLIS;
@VisibleForTesting
static final long DEFAULT_UNSEEN_CONSTRAINT_GRACE_PERIOD_MS = 3 * DAY_IN_MILLIS;
diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
index a3a686f..a0b9c5f 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
@@ -16,8 +16,6 @@
package com.android.server.job.controllers;
-import static android.text.format.DateUtils.HOUR_IN_MILLIS;
-
import static com.android.server.job.JobSchedulerService.ACTIVE_INDEX;
import static com.android.server.job.JobSchedulerService.EXEMPTED_INDEX;
import static com.android.server.job.JobSchedulerService.NEVER_INDEX;
@@ -430,9 +428,6 @@
*/
public static final int INTERNAL_FLAG_DEMOTED_BY_SYSTEM_UIJ = 1 << 2;
- /** Minimum difference between start and end time to have flexible constraint */
- @VisibleForTesting
- static final long MIN_WINDOW_FOR_FLEXIBILITY_MS = HOUR_IN_MILLIS;
/**
* Versatile, persistable flags for a job that's updated within the system server,
* as opposed to {@link JobInfo#flags} that's set by callers.
@@ -708,14 +703,10 @@
final boolean lacksSomeFlexibleConstraints =
((~requiredConstraints) & SYSTEM_WIDE_FLEXIBLE_CONSTRAINTS) != 0
|| mCanApplyTransportAffinities;
- final boolean satisfiesMinWindowException =
- (latestRunTimeElapsedMillis - earliestRunTimeElapsedMillis)
- >= MIN_WINDOW_FOR_FLEXIBILITY_MS;
// The first time a job is rescheduled it will not be subject to flexible constraints.
// Otherwise, every consecutive reschedule increases a jobs' flexibility deadline.
if (!isRequestedExpeditedJob() && !job.isUserInitiated()
- && satisfiesMinWindowException
&& (numFailures + numSystemStops) != 1
&& lacksSomeFlexibleConstraints) {
requiredConstraints |= CONSTRAINT_FLEXIBLE;
diff --git a/cmds/uinput/README.md b/cmds/uinput/README.md
index f177586..b6e4e0d 100644
--- a/cmds/uinput/README.md
+++ b/cmds/uinput/README.md
@@ -154,8 +154,7 @@
#### `delay`
-Add a delay between the processing of commands. The delay will be timed from when the last delay
-ended, rather than from the current time, to allow for more precise timings to be produced.
+Add a delay to command processing
| Field | Type | Description |
|:-------------:|:-------------:|:-------------------------- |
diff --git a/cmds/uinput/jni/com_android_commands_uinput_Device.cpp b/cmds/uinput/jni/com_android_commands_uinput_Device.cpp
index bd61000..a78a465 100644
--- a/cmds/uinput/jni/com_android_commands_uinput_Device.cpp
+++ b/cmds/uinput/jni/com_android_commands_uinput_Device.cpp
@@ -166,14 +166,14 @@
::ioctl(mFd, UI_DEV_DESTROY);
}
-void UinputDevice::injectEvent(std::chrono::microseconds timestamp, uint16_t type, uint16_t code,
- int32_t value) {
+void UinputDevice::injectEvent(uint16_t type, uint16_t code, int32_t value) {
struct input_event event = {};
event.type = type;
event.code = code;
event.value = value;
- event.time.tv_sec = timestamp.count() / 1'000'000;
- event.time.tv_usec = timestamp.count() % 1'000'000;
+ timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ TIMESPEC_TO_TIMEVAL(&event.time, &ts);
if (::write(mFd, &event, sizeof(input_event)) < 0) {
ALOGE("Could not write event %" PRIu16 " %" PRIu16 " with value %" PRId32 " : %s", type,
@@ -268,12 +268,12 @@
}
}
-static void injectEvent(JNIEnv* /* env */, jclass /* clazz */, jlong ptr, jlong timestampMicros,
- jint type, jint code, jint value) {
+static void injectEvent(JNIEnv* /* env */, jclass /* clazz */, jlong ptr, jint type, jint code,
+ jint value) {
uinput::UinputDevice* d = reinterpret_cast<uinput::UinputDevice*>(ptr);
if (d != nullptr) {
- d->injectEvent(std::chrono::microseconds(timestampMicros), static_cast<uint16_t>(type),
- static_cast<uint16_t>(code), static_cast<int32_t>(value));
+ d->injectEvent(static_cast<uint16_t>(type), static_cast<uint16_t>(code),
+ static_cast<int32_t>(value));
} else {
ALOGE("Could not inject event, Device* is null!");
}
@@ -330,7 +330,7 @@
"(Ljava/lang/String;IIIIIILjava/lang/String;"
"Lcom/android/commands/uinput/Device$DeviceCallback;)J",
reinterpret_cast<void*>(openUinputDevice)},
- {"nativeInjectEvent", "(JJIII)V", reinterpret_cast<void*>(injectEvent)},
+ {"nativeInjectEvent", "(JIII)V", reinterpret_cast<void*>(injectEvent)},
{"nativeConfigure", "(II[I)V", reinterpret_cast<void*>(configure)},
{"nativeSetAbsInfo", "(IILandroid/os/Parcel;)V", reinterpret_cast<void*>(setAbsInfo)},
{"nativeCloseUinputDevice", "(J)V", reinterpret_cast<void*>(closeUinputDevice)},
diff --git a/cmds/uinput/jni/com_android_commands_uinput_Device.h b/cmds/uinput/jni/com_android_commands_uinput_Device.h
index 72c8647..9769a75 100644
--- a/cmds/uinput/jni/com_android_commands_uinput_Device.h
+++ b/cmds/uinput/jni/com_android_commands_uinput_Device.h
@@ -14,14 +14,13 @@
* limitations under the License.
*/
-#include <android-base/unique_fd.h>
-#include <jni.h>
-#include <linux/input.h>
-
-#include <chrono>
#include <memory>
#include <vector>
+#include <jni.h>
+#include <linux/input.h>
+
+#include <android-base/unique_fd.h>
#include "src/com/android/commands/uinput/InputAbsInfo.h"
namespace android {
@@ -54,8 +53,7 @@
virtual ~UinputDevice();
- void injectEvent(std::chrono::microseconds timestamp, uint16_t type, uint16_t code,
- int32_t value);
+ void injectEvent(uint16_t type, uint16_t code, int32_t value);
int handleEvents(int events);
private:
diff --git a/cmds/uinput/src/com/android/commands/uinput/Device.java b/cmds/uinput/src/com/android/commands/uinput/Device.java
index 76ab475..25d3a34 100644
--- a/cmds/uinput/src/com/android/commands/uinput/Device.java
+++ b/cmds/uinput/src/com/android/commands/uinput/Device.java
@@ -55,7 +55,7 @@
private final SparseArray<InputAbsInfo> mAbsInfo;
private final OutputStream mOutputStream;
private final Object mCond = new Object();
- private long mTimeToSendNanos;
+ private long mTimeToSend;
static {
System.loadLibrary("uinputcommand_jni");
@@ -65,8 +65,7 @@
int productId, int versionId, int bus, int ffEffectsMax, String port,
DeviceCallback callback);
private static native void nativeCloseUinputDevice(long ptr);
- private static native void nativeInjectEvent(long ptr, long timestampMicros, int type, int code,
- int value);
+ private static native void nativeInjectEvent(long ptr, int type, int code, int value);
private static native void nativeConfigure(int handle, int code, int[] configs);
private static native void nativeSetAbsInfo(int handle, int axisCode, Parcel axisParcel);
private static native int nativeGetEvdevEventTypeByLabel(String label);
@@ -102,54 +101,27 @@
}
mHandler.obtainMessage(MSG_OPEN_UINPUT_DEVICE, args).sendToTarget();
- mTimeToSendNanos = SystemClock.uptimeNanos();
- }
-
- private long getTimeToSendMillis() {
- // Since we can only specify delays in milliseconds but evemu timestamps are in
- // microseconds, we have to round up the delays to avoid setting event timestamps
- // which are in the future (which the kernel would silently reject and replace with
- // the current time).
- //
- // This should be the same as (long) Math.ceil(mTimeToSendNanos / 1_000_000.0), except
- // without the precision loss that comes from converting from long to double and back.
- return mTimeToSendNanos / 1_000_000 + ((mTimeToSendNanos % 1_000_000 > 0) ? 1 : 0);
+ mTimeToSend = SystemClock.uptimeMillis();
}
/**
* Inject uinput events to device
*
* @param events Array of raw uinput events.
- * @param offsetMicros The difference in microseconds between the timestamps of the previous
- * batch of events injected and this batch. If set to -1, the current
- * timestamp will be used.
*/
- public void injectEvent(int[] events, long offsetMicros) {
+ public void injectEvent(int[] events) {
// if two messages are sent at identical time, they will be processed in order received
- SomeArgs args = SomeArgs.obtain();
- args.arg1 = events;
- args.argl1 = offsetMicros;
- args.argl2 = mTimeToSendNanos;
- Message msg = mHandler.obtainMessage(MSG_INJECT_EVENT, args);
- mHandler.sendMessageAtTime(msg, getTimeToSendMillis());
+ Message msg = mHandler.obtainMessage(MSG_INJECT_EVENT, events);
+ mHandler.sendMessageAtTime(msg, mTimeToSend);
}
/**
- * Delay subsequent device activity by the specified amount of time.
+ * Impose a delay to the device for execution.
*
- * <p>Note that although the delay is specified in nanoseconds, due to limitations of {@link
- * Handler}'s API, scheduling only occurs with millisecond precision. When scheduling an
- * injection or sync, the time at which it is scheduled will be rounded up to the nearest
- * millisecond. While this means that a particular injection cannot be scheduled precisely,
- * rounding errors will not accumulate over time. For example, if five injections are scheduled
- * with a delay of 1,200,000ns before each one, the total delay will be 6ms, as opposed to the
- * 10ms it would have been if each individual delay had been rounded up (as {@link EvemuParser}
- * would otherwise have to do to avoid sending timestamps that are in the future).
- *
- * @param delayNanos Time to delay in unit of nanoseconds.
+ * @param delay Time to delay in unit of milliseconds.
*/
- public void addDelayNanos(long delayNanos) {
- mTimeToSendNanos += delayNanos;
+ public void addDelay(int delay) {
+ mTimeToSend = Math.max(SystemClock.uptimeMillis(), mTimeToSend) + delay;
}
/**
@@ -159,8 +131,7 @@
* @param syncToken The token for this sync command.
*/
public void syncEvent(String syncToken) {
- mHandler.sendMessageAtTime(
- mHandler.obtainMessage(MSG_SYNC_EVENT, syncToken), getTimeToSendMillis());
+ mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_SYNC_EVENT, syncToken), mTimeToSend);
}
/**
@@ -169,8 +140,7 @@
*/
public void close() {
Message msg = mHandler.obtainMessage(MSG_CLOSE_UINPUT_DEVICE);
- mHandler.sendMessageAtTime(
- msg, Math.max(SystemClock.uptimeMillis(), getTimeToSendMillis()) + 1);
+ mHandler.sendMessageAtTime(msg, Math.max(SystemClock.uptimeMillis(), mTimeToSend) + 1);
try {
synchronized (mCond) {
mCond.wait();
@@ -181,7 +151,6 @@
private class DeviceHandler extends Handler {
private long mPtr;
- private long mLastInjectTimestampMicros = -1;
private int mBarrierToken;
DeviceHandler(Looper looper) {
@@ -191,7 +160,7 @@
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
- case MSG_OPEN_UINPUT_DEVICE: {
+ case MSG_OPEN_UINPUT_DEVICE:
SomeArgs args = (SomeArgs) msg.obj;
String name = (String) args.arg1;
mPtr = nativeOpenUinputDevice(name, args.argi1 /* id */,
@@ -208,44 +177,15 @@
}
args.recycle();
break;
- }
- case MSG_INJECT_EVENT: {
- SomeArgs args = (SomeArgs) msg.obj;
- if (mPtr == 0) {
- args.recycle();
- break;
+ case MSG_INJECT_EVENT:
+ if (mPtr != 0) {
+ int[] events = (int[]) msg.obj;
+ for (int pos = 0; pos + 2 < events.length; pos += 3) {
+ nativeInjectEvent(mPtr, events[pos], events[pos + 1], events[pos + 2]);
+ }
}
- long offsetMicros = args.argl1;
- if (mLastInjectTimestampMicros == -1 || offsetMicros == -1) {
- // There's often a delay of a few milliseconds between the time specified to
- // Handler.sendMessageAtTime and the handler actually being called, due to
- // the way threads are scheduled. We don't take this into account when
- // calling addDelayNanos between the first batch of event injections (when
- // we set the "base timestamp" from which all others will be offset) and the
- // second batch, meaning that the actual time between the handler calls for
- // those batches may be less than the offset between their timestamps. When
- // that happens, we would pass a timestamp for the second batch that's
- // actually in the future. The kernel's uinput API rejects timestamps that
- // are in the future and uses the current time instead, making the reported
- // timestamps inconsistent with the recording we're replaying.
- //
- // To prevent this, we need to use the time we scheduled this first batch
- // for (in microseconds, to avoid potential rounding up from
- // getTimeToSendMillis), rather than the actual current time.
- mLastInjectTimestampMicros = args.argl2 / 1000;
- } else {
- mLastInjectTimestampMicros += offsetMicros;
- }
-
- int[] events = (int[]) args.arg1;
- for (int pos = 0; pos + 2 < events.length; pos += 3) {
- nativeInjectEvent(mPtr, mLastInjectTimestampMicros, events[pos],
- events[pos + 1], events[pos + 2]);
- }
- args.recycle();
break;
- }
- case MSG_CLOSE_UINPUT_DEVICE: {
+ case MSG_CLOSE_UINPUT_DEVICE:
if (mPtr != 0) {
nativeCloseUinputDevice(mPtr);
getLooper().quitSafely();
@@ -258,14 +198,11 @@
mCond.notify();
}
break;
- }
- case MSG_SYNC_EVENT: {
+ case MSG_SYNC_EVENT:
handleSyncEvent((String) msg.obj);
break;
- }
- default: {
+ default:
throw new IllegalArgumentException("Unknown device message");
- }
}
}
diff --git a/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java b/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java
index da99162..7652f24 100644
--- a/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java
+++ b/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java
@@ -44,7 +44,7 @@
* recordings, this will always be the same.
*/
private static final int DEVICE_ID = 1;
- private static final int REGISTRATION_DELAY_NANOS = 500_000_000;
+ private static final int REGISTRATION_DELAY_MILLIS = 500;
private static class CommentAwareReader {
private final LineNumberReader mReader;
@@ -152,7 +152,7 @@
final Event.Builder delayEb = new Event.Builder();
delayEb.setId(DEVICE_ID);
delayEb.setCommand(Event.Command.DELAY);
- delayEb.setDurationNanos(REGISTRATION_DELAY_NANOS);
+ delayEb.setDurationMillis(REGISTRATION_DELAY_MILLIS);
mQueuedEvents.add(delayEb.build());
}
@@ -175,6 +175,7 @@
throw new ParsingException(
"Invalid timestamp '" + parts[0] + "' (should contain a single '.')", mReader);
}
+ // TODO(b/310958309): use timeMicros to set the timestamp on the event being sent.
final long timeMicros =
parseLong(timeParts[0], 10) * 1_000_000 + parseInt(timeParts[1], 10);
final Event.Builder eb = new Event.Builder();
@@ -191,18 +192,21 @@
return eb.build();
} else {
final long delayMicros = timeMicros - mLastEventTimeMicros;
- eb.setTimestampOffsetMicros(delayMicros);
- if (delayMicros == 0) {
+ // The shortest delay supported by Handler.sendMessageAtTime (used for timings by the
+ // Device class) is 1ms, so ignore time differences smaller than that.
+ if (delayMicros < 1000) {
+ mLastEventTimeMicros = timeMicros;
return eb.build();
+ } else {
+ // Send a delay now, and queue the actual event for the next call.
+ mQueuedEvents.add(eb.build());
+ mLastEventTimeMicros = timeMicros;
+ final Event.Builder delayEb = new Event.Builder();
+ delayEb.setId(DEVICE_ID);
+ delayEb.setCommand(Event.Command.DELAY);
+ delayEb.setDurationMillis((int) (delayMicros / 1000));
+ return delayEb.build();
}
- // Send a delay now, and queue the actual event for the next call.
- mQueuedEvents.add(eb.build());
- mLastEventTimeMicros = timeMicros;
- final Event.Builder delayEb = new Event.Builder();
- delayEb.setId(DEVICE_ID);
- delayEb.setCommand(Event.Command.DELAY);
- delayEb.setDurationNanos(delayMicros * 1000);
- return delayEb.build();
}
}
diff --git a/cmds/uinput/src/com/android/commands/uinput/Event.java b/cmds/uinput/src/com/android/commands/uinput/Event.java
index 9e7ee09..0f16a27 100644
--- a/cmds/uinput/src/com/android/commands/uinput/Event.java
+++ b/cmds/uinput/src/com/android/commands/uinput/Event.java
@@ -99,9 +99,8 @@
private int mVersionId;
private int mBusId;
private int[] mInjections;
- private long mTimestampOffsetMicros = -1;
private SparseArray<int[]> mConfiguration;
- private long mDurationNanos;
+ private int mDurationMillis;
private int mFfEffectsMax = 0;
private String mInputPort;
private SparseArray<InputAbsInfo> mAbsInfo;
@@ -140,28 +139,19 @@
}
/**
- * Returns the number of microseconds that should be added to the previous {@code INJECT}
- * event's timestamp to produce the timestamp for this {@code INJECT} event. A value of -1
- * indicates that the current timestamp should be used instead.
- */
- public long getTimestampOffsetMicros() {
- return mTimestampOffsetMicros;
- }
-
- /**
* Returns a {@link SparseArray} describing the event codes that should be registered for the
* device. The keys are uinput ioctl codes (such as those returned from {@link
* UinputControlCode#getValue()}, while the values are arrays of event codes to be enabled with
* those ioctls. For example, key 101 (corresponding to {@link UinputControlCode#UI_SET_KEYBIT})
- * could have values 0x110 ({@code BTN_LEFT}), 0x111 ({@code BTN_RIGHT}), and 0x112
+ * could have values 0x110 ({@code BTN_LEFT}, 0x111 ({@code BTN_RIGHT}), and 0x112
* ({@code BTN_MIDDLE}).
*/
public SparseArray<int[]> getConfiguration() {
return mConfiguration;
}
- public long getDurationNanos() {
- return mDurationNanos;
+ public int getDurationMillis() {
+ return mDurationMillis;
}
public int getFfEffectsMax() {
@@ -192,7 +182,7 @@
+ ", busId=" + mBusId
+ ", events=" + Arrays.toString(mInjections)
+ ", configuration=" + mConfiguration
- + ", duration=" + mDurationNanos + "ns"
+ + ", duration=" + mDurationMillis + "ms"
+ ", ff_effects_max=" + mFfEffectsMax
+ ", port=" + mInputPort
+ "}";
@@ -221,10 +211,6 @@
mEvent.mInjections = events;
}
- public void setTimestampOffsetMicros(long offsetMicros) {
- mEvent.mTimestampOffsetMicros = offsetMicros;
- }
-
/**
* Sets the event codes that should be registered with a {@code register} command.
*
@@ -251,8 +237,8 @@
mEvent.mBusId = busId;
}
- public void setDurationNanos(long durationNanos) {
- mEvent.mDurationNanos = durationNanos;
+ public void setDurationMillis(int durationMillis) {
+ mEvent.mDurationMillis = durationMillis;
}
public void setFfEffectsMax(int ffEffectsMax) {
@@ -285,7 +271,7 @@
}
}
case DELAY -> {
- if (mEvent.mDurationNanos <= 0) {
+ if (mEvent.mDurationMillis <= 0) {
throw new IllegalStateException("Delay has missing or invalid duration");
}
}
diff --git a/cmds/uinput/src/com/android/commands/uinput/JsonStyleParser.java b/cmds/uinput/src/com/android/commands/uinput/JsonStyleParser.java
index 6994f0c..ed3ff33 100644
--- a/cmds/uinput/src/com/android/commands/uinput/JsonStyleParser.java
+++ b/cmds/uinput/src/com/android/commands/uinput/JsonStyleParser.java
@@ -71,8 +71,7 @@
case "configuration" -> eb.setConfiguration(readConfiguration());
case "ff_effects_max" -> eb.setFfEffectsMax(readInt());
case "abs_info" -> eb.setAbsInfo(readAbsInfoArray());
- // Duration is specified in milliseconds in the JSON-style format.
- case "duration" -> eb.setDurationNanos(readInt() * 1_000_000L);
+ case "duration" -> eb.setDurationMillis(readInt());
case "port" -> eb.setInputPort(mReader.nextString());
case "syncToken" -> eb.setSyncToken(mReader.nextString());
default -> mReader.skipValue();
diff --git a/cmds/uinput/src/com/android/commands/uinput/Uinput.java b/cmds/uinput/src/com/android/commands/uinput/Uinput.java
index 760e981..04df279 100644
--- a/cmds/uinput/src/com/android/commands/uinput/Uinput.java
+++ b/cmds/uinput/src/com/android/commands/uinput/Uinput.java
@@ -134,8 +134,8 @@
switch (Objects.requireNonNull(e.getCommand())) {
case REGISTER ->
error("Device id=" + e.getId() + " is already registered. Ignoring event.");
- case INJECT -> d.injectEvent(e.getInjections(), e.getTimestampOffsetMicros());
- case DELAY -> d.addDelayNanos(e.getDurationNanos());
+ case INJECT -> d.injectEvent(e.getInjections());
+ case DELAY -> d.addDelay(e.getDurationMillis());
case SYNC -> d.syncEvent(e.getSyncToken());
}
}
diff --git a/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java b/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java
index 4dc4b68..a05cc67 100644
--- a/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java
+++ b/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java
@@ -183,22 +183,16 @@
}
private void assertInjectEvent(Event event, int eventType, int eventCode, int value) {
- assertInjectEvent(event, eventType, eventCode, value, 0);
- }
-
- private void assertInjectEvent(Event event, int eventType, int eventCode, int value,
- long timestampOffsetMicros) {
assertThat(event).isNotNull();
assertThat(event.getCommand()).isEqualTo(Event.Command.INJECT);
assertThat(event.getInjections()).asList()
.containsExactly(eventType, eventCode, value).inOrder();
- assertThat(event.getTimestampOffsetMicros()).isEqualTo(timestampOffsetMicros);
}
- private void assertDelayEvent(Event event, int durationNanos) {
+ private void assertDelayEvent(Event event, int durationMillis) {
assertThat(event).isNotNull();
assertThat(event.getCommand()).isEqualTo(Event.Command.DELAY);
- assertThat(event.getDurationNanos()).isEqualTo(durationNanos);
+ assertThat(event.getDurationMillis()).isEqualTo(durationMillis);
}
@Test
@@ -213,7 +207,7 @@
EvemuParser parser = new EvemuParser(reader);
assertThat(parser.getNextEvent().getCommand()).isEqualTo(Event.Command.REGISTER);
assertThat(parser.getNextEvent().getCommand()).isEqualTo(Event.Command.DELAY);
- assertInjectEvent(parser.getNextEvent(), 0x2, 0x0, 1, -1);
+ assertInjectEvent(parser.getNextEvent(), 0x2, 0x0, 1);
assertInjectEvent(parser.getNextEvent(), 0x2, 0x1, -2);
assertInjectEvent(parser.getNextEvent(), 0x0, 0x0, 0);
}
@@ -234,17 +228,17 @@
assertThat(parser.getNextEvent().getCommand()).isEqualTo(Event.Command.REGISTER);
assertThat(parser.getNextEvent().getCommand()).isEqualTo(Event.Command.DELAY);
- assertInjectEvent(parser.getNextEvent(), 0x1, 0x15, 1, -1);
+ assertInjectEvent(parser.getNextEvent(), 0x1, 0x15, 1);
assertInjectEvent(parser.getNextEvent(), 0x0, 0x0, 0);
- assertDelayEvent(parser.getNextEvent(), 10_000_000);
+ assertDelayEvent(parser.getNextEvent(), 10);
- assertInjectEvent(parser.getNextEvent(), 0x1, 0x15, 0, 10_000);
+ assertInjectEvent(parser.getNextEvent(), 0x1, 0x15, 0);
assertInjectEvent(parser.getNextEvent(), 0x0, 0x0, 0);
- assertDelayEvent(parser.getNextEvent(), 1_000_000_000);
+ assertDelayEvent(parser.getNextEvent(), 1000);
- assertInjectEvent(parser.getNextEvent(), 0x1, 0x15, 1, 1_000_000);
+ assertInjectEvent(parser.getNextEvent(), 0x1, 0x15, 1);
assertInjectEvent(parser.getNextEvent(), 0x0, 0x0, 0);
}
@@ -455,7 +449,7 @@
assertThat(regEvent.getBus()).isEqualTo(0x001d);
assertThat(regEvent.getVendorId()).isEqualTo(0x6cb);
assertThat(regEvent.getProductId()).isEqualTo(0x0000);
- // TODO(b/302297266): check version ID once it's supported
+ assertThat(regEvent.getVersionId()).isEqualTo(0x0000);
assertThat(regEvent.getConfiguration().get(UinputControlCode.UI_SET_PROPBIT.getValue()))
.asList().containsExactly(0, 2);
@@ -483,7 +477,7 @@
assertThat(parser.getNextEvent().getCommand()).isEqualTo(Event.Command.DELAY);
- assertInjectEvent(parser.getNextEvent(), 0x3, 0x39, 0, -1);
+ assertInjectEvent(parser.getNextEvent(), 0x3, 0x39, 0);
assertInjectEvent(parser.getNextEvent(), 0x3, 0x35, 891);
assertInjectEvent(parser.getNextEvent(), 0x3, 0x36, 333);
assertInjectEvent(parser.getNextEvent(), 0x3, 0x3a, 56);
@@ -496,8 +490,8 @@
assertInjectEvent(parser.getNextEvent(), 0x3, 0x18, 56);
assertInjectEvent(parser.getNextEvent(), 0x0, 0x0, 0);
- assertDelayEvent(parser.getNextEvent(), 6_080_000);
+ assertDelayEvent(parser.getNextEvent(), 6);
- assertInjectEvent(parser.getNextEvent(), 0x3, 0x0035, 888, 6_080);
+ assertInjectEvent(parser.getNextEvent(), 0x3, 0x0035, 888);
}
}
diff --git a/core/api/current.txt b/core/api/current.txt
index 3fde9a6..3669103 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -1804,6 +1804,7 @@
field public static final int useEmbeddedDex = 16844190; // 0x101059e
field public static final int useIntrinsicSizeAsMinimum = 16843536; // 0x1010310
field public static final int useLevel = 16843167; // 0x101019f
+ field @FlaggedApi("com.android.text.flags.fix_line_height_for_locale") public static final int useLocalePreferredLineHeightForMinimum;
field public static final int userVisible = 16843409; // 0x1010291
field public static final int usesCleartextTraffic = 16844012; // 0x10104ec
field public static final int usesPermissionFlags = 16844356; // 0x1010644
@@ -3322,11 +3323,13 @@
method @FlaggedApi("android.view.accessibility.a11y_overlay_callbacks") public void attachAccessibilityOverlayToWindow(int, @NonNull android.view.SurfaceControl, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.IntConsumer);
method public boolean clearCache();
method public boolean clearCachedSubtree(@NonNull android.view.accessibility.AccessibilityNodeInfo);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void clearTestBrailleDisplayController();
method public final void disableSelf();
method public final boolean dispatchGesture(@NonNull android.accessibilityservice.GestureDescription, @Nullable android.accessibilityservice.AccessibilityService.GestureResultCallback, @Nullable android.os.Handler);
method public android.view.accessibility.AccessibilityNodeInfo findFocus(int);
method @NonNull public final android.accessibilityservice.AccessibilityButtonController getAccessibilityButtonController();
method @NonNull public final android.accessibilityservice.AccessibilityButtonController getAccessibilityButtonController(int);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") @NonNull public android.accessibilityservice.BrailleDisplayController getBrailleDisplayController();
method @NonNull @RequiresPermission(android.Manifest.permission.USE_FINGERPRINT) public final android.accessibilityservice.FingerprintGestureController getFingerprintGestureController();
method @Nullable public final android.accessibilityservice.InputMethod getInputMethod();
method @NonNull public final android.accessibilityservice.AccessibilityService.MagnificationController getMagnificationController();
@@ -3356,6 +3359,7 @@
method public boolean setCacheEnabled(boolean);
method public void setGestureDetectionPassthroughRegion(int, @NonNull android.graphics.Region);
method public final void setServiceInfo(android.accessibilityservice.AccessibilityServiceInfo);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void setTestBrailleDisplayController(@NonNull android.accessibilityservice.BrailleDisplayController);
method public void setTouchExplorationPassthroughRegion(int, @NonNull android.graphics.Region);
method public void takeScreenshot(int, @NonNull java.util.concurrent.Executor, @NonNull android.accessibilityservice.AccessibilityService.TakeScreenshotCallback);
method public void takeScreenshotOfWindow(int, @NonNull java.util.concurrent.Executor, @NonNull android.accessibilityservice.AccessibilityService.TakeScreenshotCallback);
@@ -3560,6 +3564,25 @@
field public String[] packageNames;
}
+ @FlaggedApi("android.view.accessibility.braille_display_hid") public interface BrailleDisplayController {
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public void connect(@NonNull android.bluetooth.BluetoothDevice, @NonNull android.accessibilityservice.BrailleDisplayController.BrailleDisplayCallback);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public void connect(@NonNull android.bluetooth.BluetoothDevice, @NonNull java.util.concurrent.Executor, @NonNull android.accessibilityservice.BrailleDisplayController.BrailleDisplayCallback);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void connect(@NonNull android.hardware.usb.UsbDevice, @NonNull android.accessibilityservice.BrailleDisplayController.BrailleDisplayCallback);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void connect(@NonNull android.hardware.usb.UsbDevice, @NonNull java.util.concurrent.Executor, @NonNull android.accessibilityservice.BrailleDisplayController.BrailleDisplayCallback);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void disconnect();
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public boolean isConnected();
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void write(@NonNull byte[]) throws java.io.IOException;
+ }
+
+ @FlaggedApi("android.view.accessibility.braille_display_hid") public static interface BrailleDisplayController.BrailleDisplayCallback {
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void onConnected(@NonNull byte[]);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void onConnectionFailed(int);
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void onDisconnected();
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") public void onInput(@NonNull byte[]);
+ field @FlaggedApi("android.view.accessibility.braille_display_hid") public static final int FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND = 2; // 0x2
+ field @FlaggedApi("android.view.accessibility.braille_display_hid") public static final int FLAG_ERROR_CANNOT_ACCESS = 1; // 0x1
+ }
+
public final class FingerprintGestureController {
method public boolean isGestureDetectionAvailable();
method public void registerFingerprintGestureCallback(@NonNull android.accessibilityservice.FingerprintGestureController.FingerprintGestureCallback, @Nullable android.os.Handler);
@@ -5425,7 +5448,6 @@
}
@FlaggedApi("android.security.content_uri_permission_apis") public final class ComponentCaller {
- ctor public ComponentCaller(@NonNull android.os.IBinder, @Nullable android.os.IBinder);
method public int checkContentUriPermission(@NonNull android.net.Uri, int);
method @Nullable public String getPackage();
method public int getUid();
@@ -7402,6 +7424,7 @@
method public int onStartCommand(android.content.Intent, int, int);
method public void onTaskRemoved(android.content.Intent);
method public void onTimeout(int);
+ method @FlaggedApi("android.app.introduce_new_service_ontimeout_callback") public void onTimeout(int, int);
method public void onTrimMemory(int);
method public boolean onUnbind(android.content.Intent);
method public final void startForeground(int, android.app.Notification);
@@ -7817,6 +7840,7 @@
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.admin.DeviceAdminInfo> CREATOR;
field public static final int HEADLESS_DEVICE_OWNER_MODE_AFFILIATED = 1; // 0x1
+ field @FlaggedApi("android.app.admin.flags.headless_device_owner_single_user_enabled") public static final int HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER = 2; // 0x2
field public static final int HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED = 0; // 0x0
field public static final int USES_ENCRYPTED_STORAGE = 7; // 0x7
field public static final int USES_POLICY_DISABLE_CAMERA = 8; // 0x8
@@ -10021,11 +10045,22 @@
method public CharSequence coerceToText(android.content.Context);
method public String getHtmlText();
method public android.content.Intent getIntent();
+ method @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") @Nullable public android.app.PendingIntent getPendingIntent();
method public CharSequence getText();
method @Nullable public android.view.textclassifier.TextLinks getTextLinks();
method public android.net.Uri getUri();
}
+ @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") public static final class ClipData.Item.Builder {
+ ctor public ClipData.Item.Builder();
+ method @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") @NonNull public android.content.ClipData.Item build();
+ method @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") @NonNull public android.content.ClipData.Item.Builder setHtmlText(@Nullable String);
+ method @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") @NonNull public android.content.ClipData.Item.Builder setIntent(@Nullable android.content.Intent);
+ method @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") @NonNull public android.content.ClipData.Item.Builder setPendingIntent(@Nullable android.app.PendingIntent);
+ method @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") @NonNull public android.content.ClipData.Item.Builder setText(@Nullable CharSequence);
+ method @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") @NonNull public android.content.ClipData.Item.Builder setUri(@Nullable android.net.Uri);
+ }
+
public class ClipDescription implements android.os.Parcelable {
ctor public ClipDescription(CharSequence, String[]);
ctor public ClipDescription(android.content.ClipDescription);
@@ -11312,6 +11347,7 @@
field public static final String EXTRA_LOCALE_LIST = "android.intent.extra.LOCALE_LIST";
field public static final String EXTRA_LOCAL_ONLY = "android.intent.extra.LOCAL_ONLY";
field public static final String EXTRA_LOCUS_ID = "android.intent.extra.LOCUS_ID";
+ field @FlaggedApi("android.service.chooser.enable_sharesheet_metadata_extra") public static final String EXTRA_METADATA_TEXT = "android.intent.extra.METADATA_TEXT";
field public static final String EXTRA_MIME_TYPES = "android.intent.extra.MIME_TYPES";
field public static final String EXTRA_NOT_UNKNOWN_SOURCE = "android.intent.extra.NOT_UNKNOWN_SOURCE";
field public static final String EXTRA_ORIGINATING_URI = "android.intent.extra.ORIGINATING_URI";
@@ -18823,6 +18859,7 @@
method @FlaggedApi("android.hardware.biometrics.custom_biometric_prompt") @Nullable public android.hardware.biometrics.PromptContentView getContentView();
method @Nullable public CharSequence getDescription();
method @FlaggedApi("android.hardware.biometrics.custom_biometric_prompt") @Nullable @RequiresPermission(android.Manifest.permission.SET_BIOMETRIC_DIALOG_LOGO) public android.graphics.Bitmap getLogoBitmap();
+ method @FlaggedApi("android.hardware.biometrics.custom_biometric_prompt") @Nullable @RequiresPermission(android.Manifest.permission.SET_BIOMETRIC_DIALOG_LOGO) public String getLogoDescription();
method @FlaggedApi("android.hardware.biometrics.custom_biometric_prompt") @DrawableRes @RequiresPermission(android.Manifest.permission.SET_BIOMETRIC_DIALOG_LOGO) public int getLogoRes();
method @Nullable public CharSequence getNegativeButtonText();
method @Nullable public CharSequence getSubtitle();
@@ -18874,6 +18911,7 @@
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setDescription(@NonNull CharSequence);
method @Deprecated @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setDeviceCredentialAllowed(boolean);
method @FlaggedApi("android.hardware.biometrics.custom_biometric_prompt") @NonNull @RequiresPermission(android.Manifest.permission.SET_BIOMETRIC_DIALOG_LOGO) public android.hardware.biometrics.BiometricPrompt.Builder setLogoBitmap(@NonNull android.graphics.Bitmap);
+ method @FlaggedApi("android.hardware.biometrics.custom_biometric_prompt") @NonNull @RequiresPermission(android.Manifest.permission.SET_BIOMETRIC_DIALOG_LOGO) public android.hardware.biometrics.BiometricPrompt.Builder setLogoDescription(@NonNull String);
method @FlaggedApi("android.hardware.biometrics.custom_biometric_prompt") @NonNull @RequiresPermission(android.Manifest.permission.SET_BIOMETRIC_DIALOG_LOGO) public android.hardware.biometrics.BiometricPrompt.Builder setLogoRes(@DrawableRes int);
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setNegativeButton(@NonNull CharSequence, @NonNull java.util.concurrent.Executor, @NonNull android.content.DialogInterface.OnClickListener);
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setSubtitle(@NonNull CharSequence);
@@ -25846,6 +25884,9 @@
method public int describeContents();
method public int getErrorCode();
method public int getFinalState();
+ method @NonNull public java.util.List<android.media.metrics.MediaItemInfo> getInputMediaItemInfos();
+ method public long getOperationTypes();
+ method @Nullable public android.media.metrics.MediaItemInfo getOutputMediaItemInfo();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.media.metrics.EditingEndedEvent> CREATOR;
field public static final int ERROR_CODE_AUDIO_PROCESSING_FAILED = 18; // 0x12
@@ -25870,14 +25911,25 @@
field public static final int FINAL_STATE_CANCELED = 2; // 0x2
field public static final int FINAL_STATE_ERROR = 3; // 0x3
field public static final int FINAL_STATE_SUCCEEDED = 1; // 0x1
+ field public static final long OPERATION_TYPE_AUDIO_EDIT = 8L; // 0x8L
+ field public static final long OPERATION_TYPE_AUDIO_TRANSCODE = 2L; // 0x2L
+ field public static final long OPERATION_TYPE_AUDIO_TRANSMUX = 32L; // 0x20L
+ field public static final long OPERATION_TYPE_PAUSED = 64L; // 0x40L
+ field public static final long OPERATION_TYPE_RESUMED = 128L; // 0x80L
+ field public static final long OPERATION_TYPE_VIDEO_EDIT = 4L; // 0x4L
+ field public static final long OPERATION_TYPE_VIDEO_TRANSCODE = 1L; // 0x1L
+ field public static final long OPERATION_TYPE_VIDEO_TRANSMUX = 16L; // 0x10L
field public static final int TIME_SINCE_CREATED_UNKNOWN = -1; // 0xffffffff
}
@FlaggedApi("com.android.media.editing.flags.add_media_metrics_editing") public static final class EditingEndedEvent.Builder {
ctor public EditingEndedEvent.Builder(int);
+ method @NonNull public android.media.metrics.EditingEndedEvent.Builder addInputMediaItemInfo(@NonNull android.media.metrics.MediaItemInfo);
+ method @NonNull public android.media.metrics.EditingEndedEvent.Builder addOperationType(long);
method @NonNull public android.media.metrics.EditingEndedEvent build();
method @NonNull public android.media.metrics.EditingEndedEvent.Builder setErrorCode(int);
method @NonNull public android.media.metrics.EditingEndedEvent.Builder setMetricsBundle(@NonNull android.os.Bundle);
+ method @NonNull public android.media.metrics.EditingEndedEvent.Builder setOutputMediaItemInfo(@NonNull android.media.metrics.MediaItemInfo);
method @NonNull public android.media.metrics.EditingEndedEvent.Builder setTimeSinceCreatedMillis(@IntRange(from=android.media.metrics.EditingEndedEvent.TIME_SINCE_CREATED_UNKNOWN) long);
}
@@ -25897,6 +25949,65 @@
field @NonNull public static final android.media.metrics.LogSessionId LOG_SESSION_ID_NONE;
}
+ @FlaggedApi("com.android.media.editing.flags.add_media_metrics_editing") public final class MediaItemInfo implements android.os.Parcelable {
+ method public int describeContents();
+ method public int getAudioChannelCount();
+ method public long getAudioSampleCount();
+ method public int getAudioSampleRateHz();
+ method public long getClipDurationMillis();
+ method @NonNull public java.util.List<java.lang.String> getCodecNames();
+ method @Nullable public String getContainerMimeType();
+ method public long getDataTypes();
+ method public long getDurationMillis();
+ method @NonNull public java.util.List<java.lang.String> getSampleMimeTypes();
+ method public int getSourceType();
+ method public int getVideoDataSpace();
+ method public float getVideoFrameRate();
+ method public long getVideoSampleCount();
+ method @NonNull public android.util.Size getVideoSize();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.media.metrics.MediaItemInfo> CREATOR;
+ field public static final long DATA_TYPE_AUDIO = 4L; // 0x4L
+ field public static final long DATA_TYPE_CUE_POINTS = 128L; // 0x80L
+ field public static final long DATA_TYPE_DEPTH = 16L; // 0x10L
+ field public static final long DATA_TYPE_GAIN_MAP = 32L; // 0x20L
+ field public static final long DATA_TYPE_GAPLESS = 256L; // 0x100L
+ field public static final long DATA_TYPE_HIGH_DYNAMIC_RANGE_VIDEO = 1024L; // 0x400L
+ field public static final long DATA_TYPE_HIGH_FRAME_RATE = 64L; // 0x40L
+ field public static final long DATA_TYPE_IMAGE = 1L; // 0x1L
+ field public static final long DATA_TYPE_METADATA = 8L; // 0x8L
+ field public static final long DATA_TYPE_SPATIAL_AUDIO = 512L; // 0x200L
+ field public static final long DATA_TYPE_VIDEO = 2L; // 0x2L
+ field public static final int SOURCE_TYPE_CAMERA = 2; // 0x2
+ field public static final int SOURCE_TYPE_EDITING_SESSION = 3; // 0x3
+ field public static final int SOURCE_TYPE_GALLERY = 1; // 0x1
+ field public static final int SOURCE_TYPE_GENERATED = 7; // 0x7
+ field public static final int SOURCE_TYPE_LOCAL_FILE = 4; // 0x4
+ field public static final int SOURCE_TYPE_REMOTE_FILE = 5; // 0x5
+ field public static final int SOURCE_TYPE_REMOTE_LIVE_STREAM = 6; // 0x6
+ field public static final int SOURCE_TYPE_UNSPECIFIED = 0; // 0x0
+ field public static final int VALUE_UNSPECIFIED = -1; // 0xffffffff
+ }
+
+ @FlaggedApi("com.android.media.editing.flags.add_media_metrics_editing") public static final class MediaItemInfo.Builder {
+ ctor public MediaItemInfo.Builder();
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder addCodecName(@NonNull String);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder addDataType(long);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder addSampleMimeType(@NonNull String);
+ method @NonNull public android.media.metrics.MediaItemInfo build();
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setAudioChannelCount(@IntRange(from=0) int);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setAudioSampleCount(@IntRange(from=0) long);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setAudioSampleRateHz(@IntRange(from=0) int);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setClipDurationMillis(long);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setContainerMimeType(@NonNull String);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setDurationMillis(long);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setSourceType(int);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setVideoDataSpace(int);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setVideoFrameRate(@FloatRange(from=0) float);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setVideoSampleCount(@IntRange(from=0) long);
+ method @NonNull public android.media.metrics.MediaItemInfo.Builder setVideoSize(@NonNull android.util.Size);
+ }
+
public final class MediaMetricsManager {
method @NonNull public android.media.metrics.BundleSession createBundleSession();
method @NonNull public android.media.metrics.EditingSession createEditingSession();
@@ -35463,7 +35574,7 @@
field public static final String LONGITUDE = "longitude";
}
- @FlaggedApi("android.provider.user_keys") public class ContactKeysManager {
+ @FlaggedApi("android.provider.user_keys") public final class ContactKeysManager {
method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.ContactKeysManager.ContactKey> getAllContactKeys(@NonNull String);
method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.ContactKeysManager.SelfKey> getAllSelfKeys();
method @Nullable @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public android.provider.ContactKeysManager.ContactKey getContactKey(@NonNull String, @NonNull String, @NonNull String);
@@ -35478,9 +35589,9 @@
method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public void updateOrInsertContactKey(@NonNull String, @NonNull String, @NonNull String, @NonNull byte[]);
method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateOrInsertSelfKey(@NonNull String, @NonNull String, @NonNull byte[]);
method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateSelfKeyRemoteVerificationState(@NonNull String, @NonNull String, int);
- field public static final int UNVERIFIED = 0; // 0x0
- field public static final int VERIFICATION_FAILED = 1; // 0x1
- field public static final int VERIFIED = 2; // 0x2
+ field public static final int VERIFICATION_STATE_UNVERIFIED = 0; // 0x0
+ field public static final int VERIFICATION_STATE_VERIFICATION_FAILED = 1; // 0x1
+ field public static final int VERIFICATION_STATE_VERIFIED = 2; // 0x2
}
public static final class ContactKeysManager.ContactKey implements android.os.Parcelable {
@@ -36977,6 +37088,7 @@
field public static final String ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS = "android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS";
field public static final String ACTION_REQUEST_MANAGE_MEDIA = "android.settings.REQUEST_MANAGE_MEDIA";
field @FlaggedApi("com.android.media.flags.enable_privileged_routing_for_media_routing_control") public static final String ACTION_REQUEST_MEDIA_ROUTING_CONTROL = "android.settings.REQUEST_MEDIA_ROUTING_CONTROL";
+ field @FlaggedApi("android.provider.backup_tasks_settings_screen") public static final String ACTION_REQUEST_RUN_BACKUP_JOBS = "android.settings.REQUEST_RUN_BACKUP_JOBS";
field public static final String ACTION_REQUEST_SCHEDULE_EXACT_ALARM = "android.settings.REQUEST_SCHEDULE_EXACT_ALARM";
field public static final String ACTION_REQUEST_SET_AUTOFILL_SERVICE = "android.settings.REQUEST_SET_AUTOFILL_SERVICE";
field @FlaggedApi("com.android.internal.telephony.flags.carrier_enabled_satellite_flag") public static final String ACTION_SATELLITE_SETTING = "android.settings.SATELLITE_SETTING";
@@ -52219,6 +52331,7 @@
method public final boolean getClipToOutline();
method @Nullable public final android.view.contentcapture.ContentCaptureSession getContentCaptureSession();
method public CharSequence getContentDescription();
+ method @FlaggedApi("android.view.flags.sensitive_content_app_protection_api") public final int getContentSensitivity();
method @UiContext public final android.content.Context getContext();
method protected android.view.ContextMenu.ContextMenuInfo getContextMenuInfo();
method public final boolean getDefaultFocusHighlightEnabled();
@@ -52398,6 +52511,7 @@
method public boolean isAttachedToWindow();
method public boolean isAutoHandwritingEnabled();
method public boolean isClickable();
+ method @FlaggedApi("android.view.flags.sensitive_content_app_protection_api") public final boolean isContentSensitive();
method public boolean isContextClickable();
method public boolean isCredential();
method public boolean isDirty();
@@ -52602,6 +52716,7 @@
method public void setClipToOutline(boolean);
method public void setContentCaptureSession(@Nullable android.view.contentcapture.ContentCaptureSession);
method public void setContentDescription(CharSequence);
+ method @FlaggedApi("android.view.flags.sensitive_content_app_protection_api") public final void setContentSensitivity(int);
method public void setContextClickable(boolean);
method public void setDefaultFocusHighlightEnabled(boolean);
method @Deprecated public void setDrawingCacheBackgroundColor(@ColorInt int);
@@ -52786,13 +52901,18 @@
field public static final int AUTOFILL_TYPE_NONE = 0; // 0x0
field public static final int AUTOFILL_TYPE_TEXT = 1; // 0x1
field public static final int AUTOFILL_TYPE_TOGGLE = 2; // 0x2
+ field @FlaggedApi("android.view.flags.sensitive_content_app_protection_api") public static final int CONTENT_SENSITIVITY_AUTO = 0; // 0x0
+ field @FlaggedApi("android.view.flags.sensitive_content_app_protection_api") public static final int CONTENT_SENSITIVITY_NOT_SENSITIVE = 2; // 0x2
+ field @FlaggedApi("android.view.flags.sensitive_content_app_protection_api") public static final int CONTENT_SENSITIVITY_SENSITIVE = 1; // 0x1
field public static final int DRAG_FLAG_ACCESSIBILITY_ACTION = 1024; // 0x400
field public static final int DRAG_FLAG_GLOBAL = 256; // 0x100
field public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 64; // 0x40
field public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 128; // 0x80
+ field @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") public static final int DRAG_FLAG_GLOBAL_SAME_APPLICATION = 4096; // 0x1000
field public static final int DRAG_FLAG_GLOBAL_URI_READ = 1; // 0x1
field public static final int DRAG_FLAG_GLOBAL_URI_WRITE = 2; // 0x2
field public static final int DRAG_FLAG_OPAQUE = 512; // 0x200
+ field @FlaggedApi("com.android.window.flags.delegate_unhandled_drags") public static final int DRAG_FLAG_START_PENDING_INTENT_ON_UNHANDLED_DRAG = 8192; // 0x2000
field @Deprecated public static final int DRAWING_CACHE_QUALITY_AUTO = 0; // 0x0
field @Deprecated public static final int DRAWING_CACHE_QUALITY_HIGH = 1048576; // 0x100000
field @Deprecated public static final int DRAWING_CACHE_QUALITY_LOW = 524288; // 0x80000
@@ -60506,6 +60626,7 @@
method public boolean isFallbackLineSpacing();
method public final boolean isHorizontallyScrollable();
method public boolean isInputMethodTarget();
+ method @FlaggedApi("com.android.text.flags.fix_line_height_for_locale") public boolean isLocalePreferredLineHeightForMinimumUsed();
method public boolean isSingleLine();
method public boolean isSuggestionsEnabled();
method public boolean isTextSelectable();
@@ -60588,6 +60709,7 @@
method public final void setLinkTextColor(@ColorInt int);
method public final void setLinkTextColor(android.content.res.ColorStateList);
method public final void setLinksClickable(boolean);
+ method @FlaggedApi("com.android.text.flags.fix_line_height_for_locale") public void setLocalePreferredLineHeightForMinimumUsed(boolean);
method public void setMarqueeRepeatLimit(int);
method public void setMaxEms(int);
method public void setMaxHeight(int);
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index 50c9c33..7936e9f 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -100,7 +100,6 @@
field public static final String CAMERA_DISABLE_TRANSMIT_LED = "android.permission.CAMERA_DISABLE_TRANSMIT_LED";
field @FlaggedApi("com.android.internal.camera.flags.camera_hsum_permission") public static final String CAMERA_HEADLESS_SYSTEM_USER = "android.permission.CAMERA_HEADLESS_SYSTEM_USER";
field public static final String CAMERA_OPEN_CLOSE_LISTENER = "android.permission.CAMERA_OPEN_CLOSE_LISTENER";
- field @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist") public static final String CAMERA_PRIVACY_ALLOWLIST = "android.permission.CAMERA_PRIVACY_ALLOWLIST";
field public static final String CAPTURE_AUDIO_HOTWORD = "android.permission.CAPTURE_AUDIO_HOTWORD";
field public static final String CAPTURE_CONSENTLESS_BUGREPORT_ON_USERDEBUG_BUILD = "android.permission.CAPTURE_CONSENTLESS_BUGREPORT_ON_USERDEBUG_BUILD";
field public static final String CAPTURE_MEDIA_OUTPUT = "android.permission.CAPTURE_MEDIA_OUTPUT";
@@ -283,6 +282,7 @@
field public static final String RADIO_SCAN_WITHOUT_LOCATION = "android.permission.RADIO_SCAN_WITHOUT_LOCATION";
field public static final String READ_ACTIVE_EMERGENCY_SESSION = "android.permission.READ_ACTIVE_EMERGENCY_SESSION";
field public static final String READ_APP_SPECIFIC_LOCALES = "android.permission.READ_APP_SPECIFIC_LOCALES";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String READ_BLOCKED_NUMBERS = "android.permission.READ_BLOCKED_NUMBERS";
field public static final String READ_CARRIER_APP_INFO = "android.permission.READ_CARRIER_APP_INFO";
field public static final String READ_CELL_BROADCASTS = "android.permission.READ_CELL_BROADCASTS";
field public static final String READ_CLIPBOARD_IN_BACKGROUND = "android.permission.READ_CLIPBOARD_IN_BACKGROUND";
@@ -410,6 +410,7 @@
field public static final String WIFI_UPDATE_COEX_UNSAFE_CHANNELS = "android.permission.WIFI_UPDATE_COEX_UNSAFE_CHANNELS";
field public static final String WIFI_UPDATE_USABILITY_STATS_SCORE = "android.permission.WIFI_UPDATE_USABILITY_STATS_SCORE";
field public static final String WRITE_ALLOWLISTED_DEVICE_CONFIG = "android.permission.WRITE_ALLOWLISTED_DEVICE_CONFIG";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String WRITE_BLOCKED_NUMBERS = "android.permission.WRITE_BLOCKED_NUMBERS";
field public static final String WRITE_DEVICE_CONFIG = "android.permission.WRITE_DEVICE_CONFIG";
field public static final String WRITE_DREAM_STATE = "android.permission.WRITE_DREAM_STATE";
field public static final String WRITE_EMBEDDED_SUBSCRIPTIONS = "android.permission.WRITE_EMBEDDED_SUBSCRIPTIONS";
@@ -1390,6 +1391,7 @@
field public static final int STATUS_DEVICE_ADMIN_NOT_SUPPORTED = 13; // 0xd
field public static final int STATUS_HAS_DEVICE_OWNER = 1; // 0x1
field public static final int STATUS_HAS_PAIRED = 8; // 0x8
+ field @FlaggedApi("android.app.admin.flags.headless_device_owner_single_user_enabled") public static final int STATUS_HEADLESS_ONLY_SYSTEM_USER = 17; // 0x11
field public static final int STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED = 16; // 0x10
field public static final int STATUS_MANAGED_USERS_NOT_SUPPORTED = 9; // 0x9
field public static final int STATUS_NONSYSTEM_USER_EXISTS = 5; // 0x5
@@ -2205,6 +2207,7 @@
method public void notifyLaunchLocationShown(@NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
method public void registerPredictionUpdates(@NonNull java.util.concurrent.Executor, @NonNull android.app.prediction.AppPredictor.Callback);
method public void requestPredictionUpdate();
+ method @FlaggedApi("android.service.appprediction.flags.service_features_api") public void requestServiceFeatures(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<android.os.Bundle>);
method @Nullable public void sortTargets(@NonNull java.util.List<android.app.prediction.AppTarget>, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.util.List<android.app.prediction.AppTarget>>);
method public void unregisterPredictionUpdates(@NonNull android.app.prediction.AppPredictor.Callback);
}
@@ -4360,10 +4363,12 @@
public final class DomainVerificationManager {
method @Nullable @RequiresPermission(android.Manifest.permission.DOMAIN_VERIFICATION_AGENT) public android.content.pm.verify.domain.DomainVerificationInfo getDomainVerificationInfo(@NonNull String) throws android.content.pm.PackageManager.NameNotFoundException;
method @NonNull @RequiresPermission(android.Manifest.permission.UPDATE_DOMAIN_VERIFICATION_USER_SELECTION) public java.util.SortedSet<android.content.pm.verify.domain.DomainOwner> getOwnersForDomain(@NonNull String);
+ method @FlaggedApi("android.content.pm.relative_reference_intent_filters") @NonNull public java.util.Map<java.lang.String,java.util.List<android.content.UriRelativeFilterGroup>> getUriRelativeFilterGroups(@NonNull String, @NonNull java.util.List<java.lang.String>);
method @NonNull @RequiresPermission(android.Manifest.permission.DOMAIN_VERIFICATION_AGENT) public java.util.List<java.lang.String> queryValidVerificationPackageNames();
method @RequiresPermission(android.Manifest.permission.UPDATE_DOMAIN_VERIFICATION_USER_SELECTION) public void setDomainVerificationLinkHandlingAllowed(@NonNull String, boolean) throws android.content.pm.PackageManager.NameNotFoundException;
method @CheckResult @RequiresPermission(android.Manifest.permission.DOMAIN_VERIFICATION_AGENT) public int setDomainVerificationStatus(@NonNull java.util.UUID, @NonNull java.util.Set<java.lang.String>, int) throws android.content.pm.PackageManager.NameNotFoundException;
method @CheckResult @RequiresPermission(android.Manifest.permission.UPDATE_DOMAIN_VERIFICATION_USER_SELECTION) public int setDomainVerificationUserSelection(@NonNull java.util.UUID, @NonNull java.util.Set<java.lang.String>, boolean) throws android.content.pm.PackageManager.NameNotFoundException;
+ method @FlaggedApi("android.content.pm.relative_reference_intent_filters") @RequiresPermission(android.Manifest.permission.DOMAIN_VERIFICATION_AGENT) public void setUriRelativeFilterGroups(@NonNull String, @NonNull java.util.Map<java.lang.String,java.util.List<android.content.UriRelativeFilterGroup>>);
field public static final int ERROR_DOMAIN_SET_ID_INVALID = 1; // 0x1
field public static final int ERROR_UNABLE_TO_APPROVE = 3; // 0x3
field public static final int ERROR_UNKNOWN_DOMAIN = 2; // 0x2
@@ -4657,15 +4662,11 @@
method @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public void addSensorPrivacyListener(@NonNull android.hardware.SensorPrivacyManager.OnSensorPrivacyChangedListener);
method @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public void addSensorPrivacyListener(@NonNull java.util.concurrent.Executor, @NonNull android.hardware.SensorPrivacyManager.OnSensorPrivacyChangedListener);
method @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public boolean areAnySensorPrivacyTogglesEnabled(int);
- method @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist") @NonNull @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public java.util.Map<java.lang.String,java.lang.Boolean> getCameraPrivacyAllowlist();
- method @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist") @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public int getSensorPrivacyState(int, int);
- method @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist") @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public boolean isCameraPrivacyEnabled(@NonNull String);
method @Deprecated @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public boolean isSensorPrivacyEnabled(int);
method @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public boolean isSensorPrivacyEnabled(int, int);
method @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public void removeSensorPrivacyListener(int, @NonNull android.hardware.SensorPrivacyManager.OnSensorPrivacyChangedListener);
method @RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) public void removeSensorPrivacyListener(@NonNull android.hardware.SensorPrivacyManager.OnSensorPrivacyChangedListener);
method @RequiresPermission(android.Manifest.permission.MANAGE_SENSOR_PRIVACY) public void setSensorPrivacy(int, boolean);
- method @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist") @RequiresPermission(android.Manifest.permission.MANAGE_SENSOR_PRIVACY) public void setSensorPrivacyState(int, int);
}
public static interface SensorPrivacyManager.OnSensorPrivacyChangedListener {
@@ -4675,7 +4676,6 @@
public static class SensorPrivacyManager.OnSensorPrivacyChangedListener.SensorPrivacyChangedParams {
method public int getSensor();
- method @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist") public int getState();
method public int getToggleType();
method public boolean isEnabled();
}
@@ -11068,6 +11068,7 @@
field public static final String USER_TYPE_FULL_SYSTEM = "android.os.usertype.full.SYSTEM";
field public static final String USER_TYPE_PROFILE_CLONE = "android.os.usertype.profile.CLONE";
field public static final String USER_TYPE_PROFILE_MANAGED = "android.os.usertype.profile.MANAGED";
+ field @FlaggedApi("android.os.allow_private_profile") public static final String USER_TYPE_PROFILE_PRIVATE = "android.os.usertype.profile.PRIVATE";
field public static final String USER_TYPE_SYSTEM_HEADLESS = "android.os.usertype.system.HEADLESS";
}
@@ -11458,6 +11459,29 @@
package android.provider {
+ public static class BlockedNumberContract.BlockedNumbers {
+ method @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") @RequiresPermission(allOf={android.Manifest.permission.READ_BLOCKED_NUMBERS, android.Manifest.permission.WRITE_BLOCKED_NUMBERS}) public static void endBlockSuppression(@NonNull android.content.Context);
+ method @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") @NonNull @RequiresPermission(allOf={android.Manifest.permission.READ_BLOCKED_NUMBERS, android.Manifest.permission.WRITE_BLOCKED_NUMBERS}) public static android.provider.BlockedNumberContract.BlockedNumbers.BlockSuppressionStatus getBlockSuppressionStatus(@NonNull android.content.Context);
+ method @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") @RequiresPermission(allOf={android.Manifest.permission.READ_BLOCKED_NUMBERS, android.Manifest.permission.WRITE_BLOCKED_NUMBERS}) public static boolean getBlockedNumberSetting(@NonNull android.content.Context, @NonNull String);
+ method @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") @RequiresPermission(allOf={android.Manifest.permission.READ_BLOCKED_NUMBERS, android.Manifest.permission.WRITE_BLOCKED_NUMBERS}) public static void notifyEmergencyContact(@NonNull android.content.Context);
+ method @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") @RequiresPermission(allOf={android.Manifest.permission.READ_BLOCKED_NUMBERS, android.Manifest.permission.WRITE_BLOCKED_NUMBERS}) public static void setBlockedNumberSetting(@NonNull android.content.Context, @NonNull String, boolean);
+ method @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") @RequiresPermission(allOf={android.Manifest.permission.READ_BLOCKED_NUMBERS, android.Manifest.permission.WRITE_BLOCKED_NUMBERS}) public static boolean shouldShowEmergencyCallNotification(@NonNull android.content.Context);
+ method @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") @RequiresPermission(allOf={android.Manifest.permission.READ_BLOCKED_NUMBERS, android.Manifest.permission.WRITE_BLOCKED_NUMBERS}) public static int shouldSystemBlockNumber(@NonNull android.content.Context, @NonNull String, int, boolean);
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String ACTION_BLOCK_SUPPRESSION_STATE_CHANGED = "android.provider.action.BLOCK_SUPPRESSION_STATE_CHANGED";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String ENHANCED_SETTING_KEY_BLOCK_PAYPHONE = "block_payphone_calls_setting";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String ENHANCED_SETTING_KEY_BLOCK_PRIVATE = "block_private_number_calls_setting";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String ENHANCED_SETTING_KEY_BLOCK_UNAVAILABLE = "block_unavailable_calls_setting";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String ENHANCED_SETTING_KEY_BLOCK_UNKNOWN = "block_unknown_calls_setting";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String ENHANCED_SETTING_KEY_BLOCK_UNREGISTERED = "block_numbers_not_in_contacts_setting";
+ field @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final String ENHANCED_SETTING_KEY_SHOW_EMERGENCY_CALL_NOTIFICATION = "show_emergency_call_notification";
+ }
+
+ @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies") public static final class BlockedNumberContract.BlockedNumbers.BlockSuppressionStatus {
+ ctor public BlockedNumberContract.BlockedNumbers.BlockSuppressionStatus(boolean, long);
+ method public boolean getIsSuppressed();
+ method public long getUntilTimestampMillis();
+ }
+
public class CallLog {
method @RequiresPermission(allOf={android.Manifest.permission.WRITE_CALL_LOG, android.Manifest.permission.INTERACT_ACROSS_USERS}) public static void storeCallComposerPicture(@NonNull android.content.Context, @NonNull java.io.InputStream, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.net.Uri,android.provider.CallLog.CallComposerLoggingException>);
}
@@ -11471,7 +11495,7 @@
field public static final int ERROR_UNKNOWN = 0; // 0x0
}
- @FlaggedApi("android.provider.user_keys") public class ContactKeysManager {
+ @FlaggedApi("android.provider.user_keys") public final class ContactKeysManager {
method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateContactKeyLocalVerificationState(@NonNull String, @NonNull String, @NonNull String, @NonNull String, int);
method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateContactKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, @NonNull String, int);
method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateSelfKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, int);
@@ -12061,6 +12085,7 @@
method @MainThread public void onDestroyPredictionSession(@NonNull android.app.prediction.AppPredictionSessionId);
method @MainThread public abstract void onLaunchLocationShown(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
method @MainThread public abstract void onRequestPredictionUpdate(@NonNull android.app.prediction.AppPredictionSessionId);
+ method @FlaggedApi("android.service.appprediction.flags.service_features_api") @MainThread public void onRequestServiceFeatures(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull java.util.function.Consumer<android.os.Bundle>);
method @MainThread public abstract void onSortAppTargets(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull java.util.List<android.app.prediction.AppTarget>, @NonNull android.os.CancellationSignal, @NonNull java.util.function.Consumer<java.util.List<android.app.prediction.AppTarget>>);
method @MainThread public void onStartPredictionUpdates();
method @MainThread public void onStopPredictionUpdates();
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index 1e30a32..a7f80dd 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -104,6 +104,14 @@
method @FlaggedApi("android.view.accessibility.motion_event_observing") public void setObservedMotionEventSources(int);
}
+ @FlaggedApi("android.view.accessibility.braille_display_hid") public interface BrailleDisplayController {
+ method @FlaggedApi("android.view.accessibility.braille_display_hid") @RequiresPermission(android.Manifest.permission.MANAGE_ACCESSIBILITY) public static void setTestBrailleDisplayData(@NonNull android.accessibilityservice.AccessibilityService, @NonNull java.util.List<android.os.Bundle>);
+ field @FlaggedApi("android.view.accessibility.braille_display_hid") public static final String TEST_BRAILLE_DISPLAY_BUS_BLUETOOTH = "BUS_BLUETOOTH";
+ field @FlaggedApi("android.view.accessibility.braille_display_hid") public static final String TEST_BRAILLE_DISPLAY_DESCRIPTOR = "DESCRIPTOR";
+ field @FlaggedApi("android.view.accessibility.braille_display_hid") public static final String TEST_BRAILLE_DISPLAY_HIDRAW_PATH = "HIDRAW_PATH";
+ field @FlaggedApi("android.view.accessibility.braille_display_hid") public static final String TEST_BRAILLE_DISPLAY_UNIQUE_ID = "UNIQUE_ID";
+ }
+
}
package android.animation {
@@ -1483,7 +1491,6 @@
public final class SensorPrivacyManager {
method @RequiresPermission(android.Manifest.permission.MANAGE_SENSOR_PRIVACY) public void setSensorPrivacy(int, int, boolean);
- method @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist") @RequiresPermission(android.Manifest.permission.MANAGE_SENSOR_PRIVACY) public void setSensorPrivacyState(int, int, int);
}
public static class SensorPrivacyManager.Sources {
@@ -2455,7 +2462,6 @@
method public boolean isVisibleBackgroundUsersOnDefaultDisplaySupported();
method public boolean isVisibleBackgroundUsersSupported();
method @Deprecated @NonNull @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_USERS, android.Manifest.permission.CREATE_USERS}) public android.content.pm.UserInfo preCreateUser(@NonNull String) throws android.os.UserManager.UserOperationException;
- field @FlaggedApi("android.os.allow_private_profile") public static final String USER_TYPE_PROFILE_PRIVATE = "android.os.usertype.profile.PRIVATE";
}
public final class VibrationAttributes implements android.os.Parcelable {
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index e7e3a85..f7d7522 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -80,6 +80,7 @@
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
@@ -850,6 +851,8 @@
private boolean mInputMethodInitialized = false;
private final SparseArray<AccessibilityButtonController> mAccessibilityButtonControllers =
new SparseArray<>(0);
+ private BrailleDisplayController mBrailleDisplayController;
+ private BrailleDisplayController mTestBrailleDisplayController;
private int mGestureStatusCallbackSequence;
@@ -3634,4 +3637,56 @@
.attachAccessibilityOverlayToWindow(
mConnectionId, accessibilityWindowId, sc, executor, callback);
}
+
+ /**
+ * Returns the {@link BrailleDisplayController} which may be used to communicate with
+ * refreshable Braille displays that provide USB or Bluetooth Braille display HID support.
+ */
+ @FlaggedApi(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @NonNull
+ public BrailleDisplayController getBrailleDisplayController() {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ synchronized (mLock) {
+ if (mTestBrailleDisplayController != null) {
+ return mTestBrailleDisplayController;
+ }
+
+ if (mBrailleDisplayController == null) {
+ mBrailleDisplayController = new BrailleDisplayControllerImpl(this, mLock);
+ }
+ return mBrailleDisplayController;
+ }
+ }
+
+ /**
+ * Set the {@link BrailleDisplayController} implementation that will be returned by
+ * {@link #getBrailleDisplayController}, to allow this accessibility service to test its
+ * interaction with BrailleDisplayController without requiring a real Braille display.
+ *
+ * <p>For full test fidelity, ensure that this test-only implementation follows the same
+ * behavior specified in the documentation for {@link BrailleDisplayController}, including
+ * thrown exceptions.
+ *
+ * @param controller A test-only implementation of {@link BrailleDisplayController}.
+ */
+ @FlaggedApi(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void setTestBrailleDisplayController(@NonNull BrailleDisplayController controller) {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ Objects.requireNonNull(controller);
+ synchronized (mLock) {
+ mTestBrailleDisplayController = controller;
+ }
+ }
+
+ /**
+ * Clears the {@link BrailleDisplayController} previously set by
+ * {@link #setTestBrailleDisplayController}.
+ */
+ @FlaggedApi(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void clearTestBrailleDisplayController() {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ synchronized (mLock) {
+ mTestBrailleDisplayController = null;
+ }
+ }
}
diff --git a/core/java/android/accessibilityservice/BrailleDisplayController.java b/core/java/android/accessibilityservice/BrailleDisplayController.java
new file mode 100644
index 0000000..5282aa3
--- /dev/null
+++ b/core/java/android/accessibilityservice/BrailleDisplayController.java
@@ -0,0 +1,308 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.accessibilityservice;
+
+import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
+import android.annotation.SuppressLint;
+import android.annotation.TestApi;
+import android.bluetooth.BluetoothDevice;
+import android.hardware.usb.UsbDevice;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.view.accessibility.AccessibilityInteractionClient;
+import android.view.accessibility.Flags;
+
+import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * Used to communicate with a Braille display that supports the Braille display HID standard
+ * (usage page 0x41).
+ *
+ * <p>Only one Braille display may be connected at a time.
+ */
+// This interface doesn't actually own resources. Its I/O connections are owned, monitored,
+// and automatically closed by the system after the accessibility service is disconnected.
+@SuppressLint("NotCloseable")
+@FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+public interface BrailleDisplayController {
+
+ /**
+ * Throw {@link IllegalStateException} if this feature's aconfig flag is disabled.
+ *
+ * @hide
+ */
+ static void checkApiFlagIsEnabled() {
+ if (!Flags.brailleDisplayHid()) {
+ throw new IllegalStateException("Flag BRAILLE_DISPLAY_HID not enabled");
+ }
+ }
+
+ /**
+ * Interface provided to {@link BrailleDisplayController} connection methods to
+ * receive callbacks from the system.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ interface BrailleDisplayCallback {
+ /**
+ * The system cannot access connected HID devices.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ int FLAG_ERROR_CANNOT_ACCESS = 1 << 0;
+ /**
+ * A unique Braille display matching the requested properties could not be identified.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ int FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND = 1 << 1;
+
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(flag = true, prefix = "FLAG_ERROR_", value = {
+ FLAG_ERROR_CANNOT_ACCESS,
+ FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND,
+ })
+ @interface ErrorCode {
+ }
+
+ /**
+ * Callback to observe a successful Braille display connection.
+ *
+ * <p>The provided HID report descriptor should be used to understand the input bytes
+ * received from the Braille display via {@link #onInput} and to prepare
+ * the output sent to the Braille display via {@link #write}.
+ *
+ * @param hidDescriptor The HID report descriptor for this Braille display.
+ * @see #connect(BluetoothDevice, BrailleDisplayCallback)
+ * @see #connect(UsbDevice, BrailleDisplayCallback)
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void onConnected(@NonNull byte[] hidDescriptor);
+
+ /**
+ * Callback to observe a failed Braille display connection.
+ *
+ * @param errorFlags A bitmask of error codes for the connection failure.
+ * @see #connect(BluetoothDevice, BrailleDisplayCallback)
+ * @see #connect(UsbDevice, BrailleDisplayCallback)
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void onConnectionFailed(@ErrorCode int errorFlags);
+
+ /**
+ * Callback to observe input bytes from the currently connected Braille display.
+ *
+ * @param input The input bytes from the Braille display, formatted according to the HID
+ * report descriptor and the HIDRAW kernel driver.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void onInput(@NonNull byte[] input);
+
+ /**
+ * Callback to observe when the currently connected Braille display is disconnected by the
+ * system.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void onDisconnected();
+ }
+
+ /**
+ * Connects to the requested bluetooth Braille display using the Braille
+ * display HID standard (usage page 0x41).
+ *
+ * <p>If successful then the HID report descriptor will be provided to
+ * {@link BrailleDisplayCallback#onConnected}
+ * and the Braille display will start sending incoming input bytes to
+ * {@link BrailleDisplayCallback#onInput}. If there is an error in reading input
+ * then the system will disconnect the Braille display.
+ *
+ * <p>Note that the callbacks will be executed on the main thread using
+ * {@link AccessibilityService#getMainExecutor()}. To specify the execution thread, use
+ * {@link #connect(BluetoothDevice, Executor, BrailleDisplayCallback)}.
+ *
+ * @param bluetoothDevice The Braille display device.
+ * @param callback Callbacks used to provide connection results.
+ * @see BrailleDisplayCallback#onConnected
+ * @see BrailleDisplayCallback#onConnectionFailed
+ * @throws IllegalStateException if a Braille display is already connected to this controller.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
+ void connect(@NonNull BluetoothDevice bluetoothDevice,
+ @NonNull BrailleDisplayCallback callback);
+
+ /**
+ * Connects to the requested bluetooth Braille display using the Braille
+ * display HID standard (usage page 0x41).
+ *
+ * <p>If successful then the HID report descriptor will be provided to
+ * {@link BrailleDisplayCallback#onConnected}
+ * and the Braille display will start sending incoming input bytes to
+ * {@link BrailleDisplayCallback#onInput}. If there is an error in reading input
+ * then the system will disconnect the Braille display.
+ *
+ * @param bluetoothDevice The Braille display device.
+ * @param callbackExecutor Executor for executing the provided callbacks.
+ * @param callback Callbacks used to provide connection results.
+ * @see BrailleDisplayCallback#onConnected
+ * @see BrailleDisplayCallback#onConnectionFailed
+ * @throws IllegalStateException if a Braille display is already connected to this controller.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
+ void connect(@NonNull BluetoothDevice bluetoothDevice,
+ @NonNull @CallbackExecutor Executor callbackExecutor,
+ @NonNull BrailleDisplayCallback callback);
+
+ /**
+ * Connects to the requested USB Braille display using the Braille
+ * display HID standard (usage page 0x41).
+ *
+ * <p>If successful then the HID report descriptor will be provided to
+ * {@link BrailleDisplayCallback#onConnected}
+ * and the Braille display will start sending incoming input bytes to
+ * {@link BrailleDisplayCallback#onInput}. If there is an error in reading input
+ * then the system will disconnect the Braille display.
+ *
+ * <p>The accessibility service app must already have approval to access the USB device
+ * from the standard {@link android.hardware.usb.UsbManager} access approval process.
+ *
+ * <p>Note that the callbacks will be executed on the main thread using
+ * {@link AccessibilityService#getMainExecutor()}. To specify the execution thread, use
+ * {@link #connect(UsbDevice, Executor, BrailleDisplayCallback)}.
+ *
+ * @param usbDevice The Braille display device.
+ * @param callback Callbacks used to provide connection results.
+ * @see BrailleDisplayCallback#onConnected
+ * @see BrailleDisplayCallback#onConnectionFailed
+ * @throws SecurityException if the caller does not have USB device approval.
+ * @throws IllegalStateException if a Braille display is already connected to this controller.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void connect(@NonNull UsbDevice usbDevice,
+ @NonNull BrailleDisplayCallback callback);
+
+ /**
+ * Connects to the requested USB Braille display using the Braille
+ * display HID standard (usage page 0x41).
+ *
+ * <p>If successful then the HID report descriptor will be provided to
+ * {@link BrailleDisplayCallback#onConnected}
+ * and the Braille display will start sending incoming input bytes to
+ * {@link BrailleDisplayCallback#onInput}. If there is an error in reading input
+ * then the system will disconnect the Braille display.
+ *
+ * <p>The accessibility service app must already have approval to access the USB device
+ * from the standard {@link android.hardware.usb.UsbManager} access approval process.
+ *
+ * @param usbDevice The Braille display device.
+ * @param callbackExecutor Executor for executing the provided callbacks.
+ * @param callback Callbacks used to provide connection results.
+ * @see BrailleDisplayCallback#onConnected
+ * @see BrailleDisplayCallback#onConnectionFailed
+ * @throws SecurityException if the caller does not have USB device approval.
+ * @throws IllegalStateException if a Braille display is already connected to this controller.
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void connect(@NonNull UsbDevice usbDevice,
+ @NonNull @CallbackExecutor Executor callbackExecutor,
+ @NonNull BrailleDisplayCallback callback);
+
+ /**
+ * Returns true if a Braille display is currently connected, otherwise false.
+ *
+ * @see #connect
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ boolean isConnected();
+
+ /**
+ * Writes a HID report to the currently connected Braille display.
+ *
+ * <p>This method returns immediately after dispatching the write request to the system.
+ * If the system experiences an error in writing output (e.g. the Braille display is unplugged
+ * after the system receives the write request but before writing the bytes to the Braille
+ * display) then the system will disconnect the Braille display, which calls
+ * {@link BrailleDisplayCallback#onDisconnected()}.
+ *
+ * @param buffer The bytes to write to the Braille display. These bytes should be formatted
+ * according to the HID report descriptor and the HIDRAW kernel driver.
+ * @throws IOException if there is no currently connected Braille display.
+ * @throws IllegalArgumentException if the buffer exceeds the maximum safe payload size for
+ * binder transactions of
+ * {@link IBinder#getSuggestedMaxIpcSizeBytes()}
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void write(@NonNull byte[] buffer) throws IOException;
+
+ /**
+ * Disconnects from the currently connected Braille display.
+ *
+ * @see #isConnected()
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ void disconnect();
+
+ /**
+ * Provides test Braille display data to be used for automated CTS tests.
+ *
+ * <p>See {@code TEST_BRAILLE_DISPLAY_*} bundle keys.
+ *
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @RequiresPermission(android.Manifest.permission.MANAGE_ACCESSIBILITY)
+ @TestApi
+ static void setTestBrailleDisplayData(
+ @NonNull AccessibilityService service,
+ @NonNull List<Bundle> brailleDisplays) {
+ checkApiFlagIsEnabled();
+ final IAccessibilityServiceConnection serviceConnection =
+ AccessibilityInteractionClient.getConnection(service.getConnectionId());
+ if (serviceConnection != null) {
+ try {
+ serviceConnection.setTestBrailleDisplayData(brailleDisplays);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /** @hide */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @TestApi
+ String TEST_BRAILLE_DISPLAY_HIDRAW_PATH = "HIDRAW_PATH";
+ /** @hide */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @TestApi
+ String TEST_BRAILLE_DISPLAY_DESCRIPTOR = "DESCRIPTOR";
+ /** @hide */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @TestApi
+ String TEST_BRAILLE_DISPLAY_BUS_BLUETOOTH = "BUS_BLUETOOTH";
+ /** @hide */
+ @FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+ @TestApi
+ String TEST_BRAILLE_DISPLAY_UNIQUE_ID = "UNIQUE_ID";
+}
diff --git a/core/java/android/accessibilityservice/BrailleDisplayControllerImpl.java b/core/java/android/accessibilityservice/BrailleDisplayControllerImpl.java
new file mode 100644
index 0000000..cac1dc4
--- /dev/null
+++ b/core/java/android/accessibilityservice/BrailleDisplayControllerImpl.java
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.accessibilityservice;
+
+import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
+import android.bluetooth.BluetoothDevice;
+import android.hardware.usb.UsbDevice;
+import android.os.Binder;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.view.accessibility.AccessibilityInteractionClient;
+import android.view.accessibility.Flags;
+
+import com.android.internal.util.FunctionalUtils;
+
+import java.io.IOException;
+import java.util.Objects;
+import java.util.concurrent.Executor;
+
+/**
+ * Default implementation of {@link BrailleDisplayController}.
+ */
+// BrailleDisplayControllerImpl is not an API, but it implements BrailleDisplayController APIs.
+// This @FlaggedApi annotation tells the linter that this method delegates API checks to its
+// callers.
+@FlaggedApi(Flags.FLAG_BRAILLE_DISPLAY_HID)
+final class BrailleDisplayControllerImpl implements BrailleDisplayController {
+
+ private final AccessibilityService mAccessibilityService;
+ private final Object mLock;
+
+ private IBrailleDisplayConnection mBrailleDisplayConnection;
+ private Executor mCallbackExecutor;
+ private BrailleDisplayCallback mCallback;
+
+ BrailleDisplayControllerImpl(AccessibilityService accessibilityService,
+ Object lock) {
+ mAccessibilityService = accessibilityService;
+ mLock = lock;
+ }
+
+ @Override
+ @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
+ public void connect(@NonNull BluetoothDevice bluetoothDevice,
+ @NonNull BrailleDisplayCallback callback) {
+ connect(bluetoothDevice, mAccessibilityService.getMainExecutor(), callback);
+ }
+
+ @Override
+ @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
+ public void connect(@NonNull BluetoothDevice bluetoothDevice,
+ @NonNull @CallbackExecutor Executor callbackExecutor,
+ @NonNull BrailleDisplayCallback callback) {
+ Objects.requireNonNull(bluetoothDevice);
+ Objects.requireNonNull(callbackExecutor);
+ Objects.requireNonNull(callback);
+ connect(serviceConnection -> serviceConnection.connectBluetoothBrailleDisplay(
+ bluetoothDevice.getAddress(), new IBrailleDisplayControllerWrapper()),
+ callbackExecutor, callback);
+ }
+
+ @Override
+ public void connect(@NonNull UsbDevice usbDevice,
+ @NonNull BrailleDisplayCallback callback) {
+ connect(usbDevice, mAccessibilityService.getMainExecutor(), callback);
+ }
+
+ @Override
+ public void connect(@NonNull UsbDevice usbDevice,
+ @NonNull @CallbackExecutor Executor callbackExecutor,
+ @NonNull BrailleDisplayCallback callback) {
+ Objects.requireNonNull(usbDevice);
+ Objects.requireNonNull(callbackExecutor);
+ Objects.requireNonNull(callback);
+ connect(serviceConnection -> serviceConnection.connectUsbBrailleDisplay(
+ usbDevice, new IBrailleDisplayControllerWrapper()),
+ callbackExecutor, callback);
+ }
+
+ /**
+ * Shared implementation for the {@code connect()} API methods.
+ *
+ * <p>Performs a blocking call to system_server to create the connection. Success is
+ * returned through {@link BrailleDisplayCallback#onConnected} while normal connection
+ * errors are returned through {@link BrailleDisplayCallback#onConnectionFailed}. This
+ * connection is implemented using cached data from the HIDRAW driver so it returns
+ * quickly without needing to perform any I/O with the Braille display.
+ *
+ * <p>The AIDL call to system_server is blocking (not posted to a handler thread) so
+ * that runtime exceptions signaling abnormal connection errors from API misuse
+ * (e.g. lacking permissions, providing an invalid BluetoothDevice, calling connect
+ * while already connected) are propagated to the API caller.
+ */
+ private void connect(
+ FunctionalUtils.RemoteExceptionIgnoringConsumer<IAccessibilityServiceConnection>
+ createConnection,
+ @NonNull Executor callbackExecutor, @NonNull BrailleDisplayCallback callback) {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ if (isConnected()) {
+ throw new IllegalStateException(
+ "This service already has a connected Braille display");
+ }
+ final IAccessibilityServiceConnection serviceConnection =
+ AccessibilityInteractionClient.getConnection(
+ mAccessibilityService.getConnectionId());
+ if (serviceConnection == null) {
+ throw new IllegalStateException("Accessibility service is not connected");
+ }
+ synchronized (mLock) {
+ mCallbackExecutor = callbackExecutor;
+ mCallback = callback;
+ }
+ try {
+ createConnection.acceptOrThrow(serviceConnection);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ @Override
+ public boolean isConnected() {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ return mBrailleDisplayConnection != null;
+ }
+
+ @Override
+ public void write(@NonNull byte[] buffer) throws IOException {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ Objects.requireNonNull(buffer);
+ if (buffer.length > IBinder.getSuggestedMaxIpcSizeBytes()) {
+ // This same check must be performed in the system to prevent reflection misuse,
+ // but perform it here too to prevent unnecessary IPCs from non-reflection callers.
+ throw new IllegalArgumentException("Invalid write buffer size " + buffer.length);
+ }
+ synchronized (mLock) {
+ if (mBrailleDisplayConnection == null) {
+ throw new IOException("Braille display is not connected");
+ }
+ try {
+ mBrailleDisplayConnection.write(buffer);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ @Override
+ public void disconnect() {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ synchronized (mLock) {
+ try {
+ if (mBrailleDisplayConnection != null) {
+ mBrailleDisplayConnection.disconnect();
+ }
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ } finally {
+ clearConnectionLocked();
+ }
+ }
+ }
+
+ /**
+ * Implementation of the {@code IBrailleDisplayController} AIDL interface provided to
+ * system_server, which system_server uses to pass messages back to this
+ * {@code BrailleDisplayController}.
+ *
+ * <p>Messages from system_server are routed to the {@link BrailleDisplayCallback} callbacks
+ * implemented by the accessibility service.
+ *
+ * <p>Note: Per API Guidelines 7.5 the Binder identity must be cleared before invoking the
+ * callback executor so that Binder identity checks in the callbacks are performed using the
+ * app's identity.
+ */
+ private final class IBrailleDisplayControllerWrapper extends IBrailleDisplayController.Stub {
+ /**
+ * Called when the system successfully connects to a Braille display.
+ */
+ @Override
+ public void onConnected(IBrailleDisplayConnection connection, byte[] hidDescriptor) {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ synchronized (mLock) {
+ mBrailleDisplayConnection = connection;
+ mCallbackExecutor.execute(() -> mCallback.onConnected(hidDescriptor));
+ }
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ }
+
+ /**
+ * Called when the system is unable to connect to a Braille display.
+ */
+ @Override
+ public void onConnectionFailed(@BrailleDisplayCallback.ErrorCode int errorCode) {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ synchronized (mLock) {
+ mCallbackExecutor.execute(() -> mCallback.onConnectionFailed(errorCode));
+ }
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ }
+
+ /**
+ * Called when input is received from the currently connected Braille display.
+ */
+ @Override
+ public void onInput(byte[] input) {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ synchronized (mLock) {
+ // Ignore input that arrives after disconnection.
+ if (mBrailleDisplayConnection != null) {
+ mCallbackExecutor.execute(() -> mCallback.onInput(input));
+ }
+ }
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ }
+
+ /**
+ * Called when the currently connected Braille display is disconnected.
+ */
+ @Override
+ public void onDisconnected() {
+ BrailleDisplayController.checkApiFlagIsEnabled();
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ synchronized (mLock) {
+ mCallbackExecutor.execute(mCallback::onDisconnected);
+ clearConnectionLocked();
+ }
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ }
+ }
+
+ private void clearConnectionLocked() {
+ mBrailleDisplayConnection = null;
+ }
+
+}
diff --git a/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl b/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl
index 96716db..dc5c7f6 100644
--- a/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl
+++ b/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl
@@ -17,10 +17,12 @@
package android.accessibilityservice;
import android.accessibilityservice.AccessibilityServiceInfo;
+import android.accessibilityservice.IBrailleDisplayController;
import android.accessibilityservice.MagnificationConfig;
import android.content.pm.ParceledListSlice;
import android.graphics.Bitmap;
import android.graphics.Region;
+import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.RemoteCallback;
import android.view.MagnificationSpec;
@@ -160,4 +162,12 @@
void attachAccessibilityOverlayToDisplay(int interactionId, int displayId, in SurfaceControl sc, IAccessibilityInteractionConnectionCallback callback);
void attachAccessibilityOverlayToWindow(int interactionId, int accessibilityWindowId, in SurfaceControl sc, IAccessibilityInteractionConnectionCallback callback);
+
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
+ void connectBluetoothBrailleDisplay(in String bluetoothAddress, in IBrailleDisplayController controller);
+
+ void connectUsbBrailleDisplay(in UsbDevice usbDevice, in IBrailleDisplayController controller);
+
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.MANAGE_ACCESSIBILITY)")
+ void setTestBrailleDisplayData(in List<Bundle> brailleDisplays);
}
\ No newline at end of file
diff --git a/core/java/android/accessibilityservice/IBrailleDisplayConnection.aidl b/core/java/android/accessibilityservice/IBrailleDisplayConnection.aidl
new file mode 100644
index 0000000..ec4d7b1
--- /dev/null
+++ b/core/java/android/accessibilityservice/IBrailleDisplayConnection.aidl
@@ -0,0 +1,12 @@
+package android.accessibilityservice;
+
+/**
+ * Interface given to a BrailleDisplayController to talk to a BrailleDisplayConnection
+ * in system_server.
+ *
+ * @hide
+ */
+interface IBrailleDisplayConnection {
+ oneway void disconnect();
+ oneway void write(in byte[] output);
+}
\ No newline at end of file
diff --git a/core/java/android/accessibilityservice/IBrailleDisplayController.aidl b/core/java/android/accessibilityservice/IBrailleDisplayController.aidl
new file mode 100644
index 0000000..7a5d83e
--- /dev/null
+++ b/core/java/android/accessibilityservice/IBrailleDisplayController.aidl
@@ -0,0 +1,17 @@
+package android.accessibilityservice;
+
+import android.accessibilityservice.IBrailleDisplayConnection;
+
+/**
+ * Interface given to a BrailleDisplayConnection to talk to a BrailleDisplayController
+ * in an accessibility service.
+ *
+ * IPCs from system_server to apps must be oneway, so designate this entire interface as oneway.
+ * @hide
+ */
+oneway interface IBrailleDisplayController {
+ void onConnected(in IBrailleDisplayConnection connection, in byte[] hidDescriptor);
+ void onConnectionFailed(int error);
+ void onInput(in byte[] input);
+ void onDisconnected();
+}
\ No newline at end of file
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 2c00c99..de6a848 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -1232,6 +1232,15 @@
}
@Override
+ public final void scheduleTimeoutServiceForType(IBinder token, int startId, int fgsType) {
+ if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
+ Trace.instant(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ "scheduleTimeoutServiceForType. token=" + token);
+ }
+ sendMessage(H.TIMEOUT_SERVICE_FOR_TYPE, token, startId, fgsType);
+ }
+
+ @Override
public final void bindApplication(
String processName,
ApplicationInfo appInfo,
@@ -2288,6 +2297,8 @@
public static final int INSTRUMENT_WITHOUT_RESTART = 170;
public static final int FINISH_INSTRUMENTATION_WITHOUT_RESTART = 171;
+ public static final int TIMEOUT_SERVICE_FOR_TYPE = 172;
+
String codeToString(int code) {
if (DEBUG_MESSAGES) {
switch (code) {
@@ -2341,6 +2352,7 @@
case DUMP_RESOURCES: return "DUMP_RESOURCES";
case TIMEOUT_SERVICE: return "TIMEOUT_SERVICE";
case PING: return "PING";
+ case TIMEOUT_SERVICE_FOR_TYPE: return "TIMEOUT_SERVICE_FOR_TYPE";
}
}
return Integer.toString(code);
@@ -2427,6 +2439,14 @@
case PING:
((RemoteCallback) msg.obj).sendResult(null);
break;
+ case TIMEOUT_SERVICE_FOR_TYPE:
+ if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
+ Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ "serviceTimeoutForType: " + msg.obj);
+ }
+ handleTimeoutServiceForType((IBinder) msg.obj, msg.arg1, msg.arg2);
+ Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
+ break;
case CONFIGURATION_CHANGED:
mConfigurationController.handleConfigurationChanged((Configuration) msg.obj);
break;
@@ -5136,6 +5156,26 @@
Slog.wtf(TAG, "handleTimeoutService: token=" + token + " not found.");
}
}
+
+ private void handleTimeoutServiceForType(IBinder token, int startId, int fgsType) {
+ Service s = mServices.get(token);
+ if (s != null) {
+ try {
+ if (localLOGV) Slog.v(TAG, "Timeout service " + s);
+
+ s.callOnTimeLimitExceeded(startId, fgsType);
+ } catch (Exception e) {
+ if (!mInstrumentation.onException(s, e)) {
+ throw new RuntimeException(
+ "Unable to call onTimeLimitExceeded on service " + s + ": " + e, e);
+ }
+ Slog.i(TAG, "handleTimeoutServiceForType: exception for " + token, e);
+ }
+ } else {
+ Slog.wtf(TAG, "handleTimeoutServiceForType: token=" + token + " not found.");
+ }
+ }
+
/**
* Resume the activity.
* @param r Target activity record.
diff --git a/core/java/android/app/ComponentCaller.java b/core/java/android/app/ComponentCaller.java
index a440dbc..44e8a0a 100644
--- a/core/java/android/app/ComponentCaller.java
+++ b/core/java/android/app/ComponentCaller.java
@@ -42,6 +42,9 @@
private final IBinder mActivityToken;
private final IBinder mCallerToken;
+ /**
+ * @hide
+ */
public ComponentCaller(@NonNull IBinder activityToken, @Nullable IBinder callerToken) {
mActivityToken = activityToken;
mCallerToken = callerToken;
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index ceeaf5d..cc0aafd 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -942,6 +942,8 @@
/** Returns if the service is a short-service is still "alive" and past the timeout. */
boolean shouldServiceTimeOut(in ComponentName className, in IBinder token);
+ /** Returns if the service has a time-limit restricted type and is past the time limit. */
+ boolean hasServiceTimeLimitExceeded(in ComponentName className, in IBinder token);
void registerUidFrozenStateChangedCallback(in IUidFrozenStateChangedCallback callback);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)")
diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl
index 59e0e99..a04620c 100644
--- a/core/java/android/app/IApplicationThread.aidl
+++ b/core/java/android/app/IApplicationThread.aidl
@@ -178,5 +178,6 @@
in TranslationSpec targetSpec, in List<AutofillId> viewIds,
in UiTranslationSpec uiTranslationSpec);
void scheduleTimeoutService(IBinder token, int startId);
+ void scheduleTimeoutServiceForType(IBinder token, int startId, int fgsType);
void schedulePing(in RemoteCallback pong);
}
diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java
index 24a5157..6255260 100644
--- a/core/java/android/app/ResourcesManager.java
+++ b/core/java/android/app/ResourcesManager.java
@@ -550,7 +550,7 @@
@UnsupportedAppUsage
protected @Nullable AssetManager createAssetManager(@NonNull final ResourcesKey key,
@Nullable ApkAssetsSupplier apkSupplier) {
- final AssetManager.Builder builder = new AssetManager.Builder();
+ final AssetManager.Builder builder = new AssetManager.Builder().setNoInit();
final ArrayList<ApkKey> apkKeys = extractApkKeys(key);
for (int i = 0, n = apkKeys.size(); i < n; i++) {
@@ -1555,7 +1555,7 @@
} else if(overlayPaths == null) {
return ArrayUtils.cloneOrNull(resourceDirs);
} else {
- final ArrayList<String> paths = new ArrayList<>();
+ final var paths = new ArrayList<String>(overlayPaths.length + resourceDirs.length);
for (final String path : overlayPaths) {
paths.add(path);
}
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index a155457..d470299 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -20,6 +20,7 @@
import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
import static android.text.TextUtils.formatSimple;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -1161,4 +1162,37 @@
*/
public void onTimeout(int startId) {
}
+
+ /** @hide */
+ public final void callOnTimeLimitExceeded(int startId, int fgsType) {
+ // Note, because all the service callbacks (and other similar callbacks, e.g. activity
+ // callbacks) are delivered using the main handler, it's possible the service is already
+ // stopped when before this method is called, so we do a double check here.
+ if (mToken == null) {
+ Log.w(TAG, "Service already destroyed, skipping onTimeLimitExceeded()");
+ return;
+ }
+ try {
+ if (!mActivityManager.hasServiceTimeLimitExceeded(
+ new ComponentName(this, mClassName), mToken)) {
+ Log.w(TAG, "Service no longer relevant, skipping onTimeLimitExceeded()");
+ return;
+ }
+ } catch (RemoteException ex) {
+ }
+ if (Flags.introduceNewServiceOntimeoutCallback()) {
+ onTimeout(startId, fgsType);
+ }
+ }
+
+ /**
+ * Callback called when a particular foreground service type has timed out.
+ *
+ * @param startId the startId passed to {@link #onStartCommand(Intent, int, int)} when
+ * the service started.
+ * @param fgsType the foreground service type which caused the timeout.
+ */
+ @FlaggedApi(Flags.FLAG_INTRODUCE_NEW_SERVICE_ONTIMEOUT_CALLBACK)
+ public void onTimeout(int startId, int fgsType) {
+ }
}
diff --git a/core/java/android/app/activity_manager.aconfig b/core/java/android/app/activity_manager.aconfig
index c0b299b..ff23f09 100644
--- a/core/java/android/app/activity_manager.aconfig
+++ b/core/java/android/app/activity_manager.aconfig
@@ -27,3 +27,10 @@
description: "API to add OnUidImportanceListener with targetted UIDs"
bug: "286258140"
}
+
+flag {
+ namespace: "backstage_power"
+ name: "introduce_new_service_ontimeout_callback"
+ description: "Add a new callback in Service to indicate a FGS has reached its timeout."
+ bug: "317799821"
+}
diff --git a/core/java/android/app/admin/DeviceAdminInfo.java b/core/java/android/app/admin/DeviceAdminInfo.java
index 14462b8..7d5d5c1 100644
--- a/core/java/android/app/admin/DeviceAdminInfo.java
+++ b/core/java/android/app/admin/DeviceAdminInfo.java
@@ -16,8 +16,10 @@
package android.app.admin;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.app.admin.flags.Flags;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
@@ -176,7 +178,18 @@
*/
public static final int HEADLESS_DEVICE_OWNER_MODE_AFFILIATED = 1;
- @IntDef({HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED, HEADLESS_DEVICE_OWNER_MODE_AFFILIATED})
+ /**
+ * Value for {@link #getHeadlessDeviceOwnerMode} which indicates that this DPC should be
+ * provisioned into the first secondary user when on a Headless System User Mode device.
+ *
+ * <p>This mode only allows a single secondary user on the device blocking the creation of
+ * additional secondary users.
+ */
+ @FlaggedApi(Flags.FLAG_HEADLESS_DEVICE_OWNER_SINGLE_USER_ENABLED)
+ public static final int HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER = 2;
+
+ @IntDef({HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED, HEADLESS_DEVICE_OWNER_MODE_AFFILIATED,
+ HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER})
@Retention(RetentionPolicy.SOURCE)
private @interface HeadlessDeviceOwnerMode {}
@@ -373,6 +386,8 @@
mHeadlessDeviceOwnerMode = HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
} else if (deviceOwnerModeStringValue.equalsIgnoreCase("affiliated")) {
mHeadlessDeviceOwnerMode = HEADLESS_DEVICE_OWNER_MODE_AFFILIATED;
+ } else if (deviceOwnerModeStringValue.equalsIgnoreCase("single_user")) {
+ mHeadlessDeviceOwnerMode = HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER;
} else {
throw new XmlPullParserException("headless-system-user mode must be valid");
}
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index c8762c6..c649e62 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -84,6 +84,7 @@
import android.app.IServiceConnection;
import android.app.KeyguardManager;
import android.app.admin.SecurityLog.SecurityEvent;
+import android.app.admin.flags.Flags;
import android.app.compat.CompatChanges;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledSince;
@@ -2863,6 +2864,19 @@
public static final int STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED = 16;
/**
+ * Result code for {@link #checkProvisioningPrecondition}.
+ *
+ * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when provisioning a DPC into the
+ * {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER} mode but only the system
+ * user exists on the device.
+ *
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_HEADLESS_DEVICE_OWNER_SINGLE_USER_ENABLED)
+ public static final int STATUS_HEADLESS_ONLY_SYSTEM_USER = 17;
+
+ /**
* Result codes for {@link #checkProvisioningPrecondition} indicating all the provisioning pre
* conditions.
*
@@ -2876,7 +2890,7 @@
STATUS_CANNOT_ADD_MANAGED_PROFILE, STATUS_DEVICE_ADMIN_NOT_SUPPORTED,
STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER,
STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS,
- STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED
+ STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED, STATUS_HEADLESS_ONLY_SYSTEM_USER
})
public @interface ProvisioningPrecondition {}
@@ -9178,9 +9192,11 @@
* <p>Calling this after the setup phase of the device owner user has completed is allowed only
* if the caller is the {@link Process#SHELL_UID Shell UID}, and there are no additional users
* (except when the device runs on headless system user mode, in which case it could have exact
- * one extra user, which is the current user - the device owner will be set in the
- * {@link UserHandle#SYSTEM system} user and a profile owner will be set in the current user)
- * and no accounts.
+ * one extra user, which is the current user.
+ *
+ * <p>On a headless devices, if it is in affiliated mode the device owner will be set in the
+ * {@link UserHandle#SYSTEM system} user. If the device is in single user mode, the device owner
+ * will be set in the first secondary user.
*
* @param who the component name to be registered as device owner.
* @param userId ID of the user on which the device owner runs.
@@ -11371,7 +11387,9 @@
* @see UserHandle
* @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
* user could not be created.
- * @throws SecurityException if {@code admin} is not a device owner.
+ * @throws SecurityException if headless device is in
+ * {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER} mode.
+ * @throws SecurityException if {@code admin} is not a device owner
* @throws UserOperationException if the user could not be created and the calling app is
* targeting {@link android.os.Build.VERSION_CODES#P} and running on
* {@link android.os.Build.VERSION_CODES#P}.
@@ -16612,7 +16630,10 @@
* before calling this method.
*
* <p>Holders of {@link android.Manifest.permission#PROVISION_DEMO_DEVICE} can call this API
- * only if {@link FullyManagedDeviceProvisioningParams#isDemoDevice()} is {@code true}.</p>
+ * only if {@link FullyManagedDeviceProvisioningParams#isDemoDevice()} is {@code true}.
+ *
+ * <p>If headless device is in {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER}
+ * mode then it sets the device owner on the first secondary user.</p>
*
* @param provisioningParams Params required to provision a fully managed device,
* see {@link FullyManagedDeviceProvisioningParams}.
diff --git a/core/java/android/app/admin/flags/flags.aconfig b/core/java/android/app/admin/flags/flags.aconfig
index 6cc8af8..3c98ef9 100644
--- a/core/java/android/app/admin/flags/flags.aconfig
+++ b/core/java/android/app/admin/flags/flags.aconfig
@@ -76,3 +76,10 @@
description: "Enable APIs to provision and manage eSIMs"
bug: "295301164"
}
+
+flag {
+ name: "headless_device_owner_single_user_enabled"
+ namespace: "enterprise"
+ description: "Add Headless DO support."
+ bug: "289515470"
+}
diff --git a/core/java/android/app/prediction/AppPredictor.java b/core/java/android/app/prediction/AppPredictor.java
index d628b7f..0c1a28a 100644
--- a/core/java/android/app/prediction/AppPredictor.java
+++ b/core/java/android/app/prediction/AppPredictor.java
@@ -16,6 +16,7 @@
package android.app.prediction;
import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
@@ -24,9 +25,12 @@
import android.content.Context;
import android.content.pm.ParceledListSlice;
import android.os.Binder;
+import android.os.Bundle;
import android.os.IBinder;
+import android.os.IRemoteCallback;
import android.os.RemoteException;
import android.os.ServiceManager;
+import android.service.appprediction.flags.Flags;
import android.util.ArrayMap;
import android.util.Log;
@@ -263,6 +267,34 @@
}
/**
+ * Requests a Bundle which includes service features info or {@code null} if the service is not
+ * available.
+ *
+ * @param callbackExecutor The callback executor to use when calling the callback. It cannot be
+ * null.
+ * @param callback The callback to return the Bundle which includes service features info. It
+ * cannot be null.
+ *
+ * @throws IllegalStateException If this AppPredictor has already been destroyed.
+ * @throws RuntimeException If there is a failure communicating with the remote service.
+ */
+ @FlaggedApi(Flags.FLAG_SERVICE_FEATURES_API)
+ public void requestServiceFeatures(@NonNull Executor callbackExecutor,
+ @NonNull Consumer<Bundle> callback) {
+ if (mIsClosed.get()) {
+ throw new IllegalStateException("This client has already been destroyed.");
+ }
+
+ try {
+ mPredictionManager.requestServiceFeatures(mSessionId,
+ new RemoteCallbackWrapper(callbackExecutor, callback));
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to request service feature info", e);
+ e.rethrowAsRuntimeException();
+ }
+ }
+
+ /**
* Destroys the client and unregisters the callback. Any method on this class after this call
* with throw {@link IllegalStateException}.
*/
@@ -347,6 +379,28 @@
}
}
+ static class RemoteCallbackWrapper extends IRemoteCallback.Stub {
+
+ private final Consumer<Bundle> mCallback;
+ private final Executor mExecutor;
+
+ RemoteCallbackWrapper(@NonNull Executor callbackExecutor,
+ @NonNull Consumer<Bundle> callback) {
+ mExecutor = callbackExecutor;
+ mCallback = callback;
+ }
+
+ @Override
+ public void sendResult(Bundle result) {
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ mExecutor.execute(() -> mCallback.accept(result));
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ }
+ }
+
private static class Token {
static final IBinder sBinder = new Binder(TAG);
}
diff --git a/core/java/android/app/prediction/IPredictionManager.aidl b/core/java/android/app/prediction/IPredictionManager.aidl
index 863fc6f9..94b4f5b 100644
--- a/core/java/android/app/prediction/IPredictionManager.aidl
+++ b/core/java/android/app/prediction/IPredictionManager.aidl
@@ -22,6 +22,7 @@
import android.app.prediction.AppPredictionSessionId;
import android.app.prediction.IPredictionCallback;
import android.content.pm.ParceledListSlice;
+import android.os.IRemoteCallback;
/**
* @hide
@@ -48,4 +49,6 @@
void requestPredictionUpdate(in AppPredictionSessionId sessionId);
void onDestroyPredictionSession(in AppPredictionSessionId sessionId);
+
+ void requestServiceFeatures(in AppPredictionSessionId sessionId, in IRemoteCallback callback);
}
diff --git a/core/java/android/content/ClipData.java b/core/java/android/content/ClipData.java
index 67759f4..eb357fe 100644
--- a/core/java/android/content/ClipData.java
+++ b/core/java/android/content/ClipData.java
@@ -21,7 +21,13 @@
import static android.content.ContentResolver.SCHEME_CONTENT;
import static android.content.ContentResolver.SCHEME_FILE;
+import static com.android.window.flags.Flags.FLAG_DELEGATE_UNHANDLED_DRAGS;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.SuppressLint;
+import android.app.PendingIntent;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
@@ -207,6 +213,7 @@
final CharSequence mText;
final String mHtmlText;
final Intent mIntent;
+ final PendingIntent mPendingIntent;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Uri mUri;
private TextLinks mTextLinks;
@@ -214,12 +221,91 @@
// if the data is obtained from {@link #copyForTransferWithActivityInfo}
private ActivityInfo mActivityInfo;
+ /**
+ * A builder for a ClipData Item.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @SuppressLint("PackageLayering")
+ public static final class Builder {
+ private CharSequence mText;
+ private String mHtmlText;
+ private Intent mIntent;
+ private PendingIntent mPendingIntent;
+ private Uri mUri;
+
+ /**
+ * Sets the text for the item to be constructed.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @NonNull
+ public Builder setText(@Nullable CharSequence text) {
+ mText = text;
+ return this;
+ }
+
+ /**
+ * Sets the HTML text for the item to be constructed.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @NonNull
+ public Builder setHtmlText(@Nullable String htmlText) {
+ mHtmlText = htmlText;
+ return this;
+ }
+
+ /**
+ * Sets the Intent for the item to be constructed.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @NonNull
+ public Builder setIntent(@Nullable Intent intent) {
+ mIntent = intent;
+ return this;
+ }
+
+ /**
+ * Sets the PendingIntent for the item to be constructed. To prevent receiving apps from
+ * improperly manipulating the intent to launch another activity as this caller, the
+ * provided PendingIntent must be immutable (see {@link PendingIntent#FLAG_IMMUTABLE}).
+ * The system will clean up the PendingIntent when it is no longer used.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @NonNull
+ public Builder setPendingIntent(@Nullable PendingIntent pendingIntent) {
+ if (pendingIntent != null && !pendingIntent.isImmutable()) {
+ throw new IllegalArgumentException("Expected pending intent to be immutable");
+ }
+ mPendingIntent = pendingIntent;
+ return this;
+ }
+
+ /**
+ * Sets the URI for the item to be constructed.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @NonNull
+ public Builder setUri(@Nullable Uri uri) {
+ mUri = uri;
+ return this;
+ }
+
+ /**
+ * Constructs a new Item with the properties set on this builder.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @NonNull
+ public Item build() {
+ return new Item(mText, mHtmlText, mIntent, mPendingIntent, mUri);
+ }
+ }
+
/** @hide */
public Item(Item other) {
mText = other.mText;
mHtmlText = other.mHtmlText;
mIntent = other.mIntent;
+ mPendingIntent = other.mPendingIntent;
mUri = other.mUri;
mActivityInfo = other.mActivityInfo;
mTextLinks = other.mTextLinks;
@@ -229,10 +315,7 @@
* Create an Item consisting of a single block of (possibly styled) text.
*/
public Item(CharSequence text) {
- mText = text;
- mHtmlText = null;
- mIntent = null;
- mUri = null;
+ this(text, null, null, null, null);
}
/**
@@ -245,30 +328,21 @@
* </p>
*/
public Item(CharSequence text, String htmlText) {
- mText = text;
- mHtmlText = htmlText;
- mIntent = null;
- mUri = null;
+ this(text, htmlText, null, null, null);
}
/**
* Create an Item consisting of an arbitrary Intent.
*/
public Item(Intent intent) {
- mText = null;
- mHtmlText = null;
- mIntent = intent;
- mUri = null;
+ this(null, null, intent, null, null);
}
/**
* Create an Item consisting of an arbitrary URI.
*/
public Item(Uri uri) {
- mText = null;
- mHtmlText = null;
- mIntent = null;
- mUri = uri;
+ this(null, null, null, null, uri);
}
/**
@@ -276,10 +350,7 @@
* text, Intent, and/or URI.
*/
public Item(CharSequence text, Intent intent, Uri uri) {
- mText = text;
- mHtmlText = null;
- mIntent = intent;
- mUri = uri;
+ this(text, null, intent, null, uri);
}
/**
@@ -289,6 +360,14 @@
* will not be done from HTML formatted text into plain text.
*/
public Item(CharSequence text, String htmlText, Intent intent, Uri uri) {
+ this(text, htmlText, intent, null, uri);
+ }
+
+ /**
+ * Builder ctor.
+ */
+ private Item(CharSequence text, String htmlText, Intent intent, PendingIntent pendingIntent,
+ Uri uri) {
if (htmlText != null && text == null) {
throw new IllegalArgumentException(
"Plain text must be supplied if HTML text is supplied");
@@ -296,6 +375,7 @@
mText = text;
mHtmlText = htmlText;
mIntent = intent;
+ mPendingIntent = pendingIntent;
mUri = uri;
}
@@ -321,6 +401,15 @@
}
/**
+ * Returns the pending intent in this Item.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ @Nullable
+ public PendingIntent getPendingIntent() {
+ return mPendingIntent;
+ }
+
+ /**
* Retrieve the raw URI contained in this Item.
*/
public Uri getUri() {
@@ -777,7 +866,7 @@
throw new NullPointerException("item is null");
}
mIcon = null;
- mItems = new ArrayList<Item>();
+ mItems = new ArrayList<>();
mItems.add(item);
mClipDescription.setIsStyledText(isStyledText());
}
@@ -794,7 +883,7 @@
throw new NullPointerException("item is null");
}
mIcon = null;
- mItems = new ArrayList<Item>();
+ mItems = new ArrayList<>();
mItems.add(item);
mClipDescription.setIsStyledText(isStyledText());
}
@@ -826,7 +915,7 @@
public ClipData(ClipData other) {
mClipDescription = other.mClipDescription;
mIcon = other.mIcon;
- mItems = new ArrayList<Item>(other.mItems);
+ mItems = new ArrayList<>(other.mItems);
}
/**
@@ -1042,6 +1131,35 @@
}
/**
+ * Checks if this clip data has a pending intent that is an activity type.
+ * @hide
+ */
+ public boolean hasActivityPendingIntents() {
+ final int size = mItems.size();
+ for (int i = 0; i < size; i++) {
+ final Item item = mItems.get(i);
+ if (item.mPendingIntent != null && item.mPendingIntent.isActivity()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Cleans up all pending intents in the ClipData.
+ * @hide
+ */
+ public void cleanUpPendingIntents() {
+ final int size = mItems.size();
+ for (int i = 0; i < size; i++) {
+ final Item item = mItems.get(i);
+ if (item.mPendingIntent != null) {
+ item.mPendingIntent.cancel();
+ }
+ }
+ }
+
+ /**
* Prepare this {@link ClipData} to leave an app process.
*
* @hide
@@ -1243,6 +1361,7 @@
TextUtils.writeToParcel(item.mText, dest, flags);
dest.writeString8(item.mHtmlText);
dest.writeTypedObject(item.mIntent, flags);
+ dest.writeTypedObject(item.mPendingIntent, flags);
dest.writeTypedObject(item.mUri, flags);
dest.writeTypedObject(mParcelItemActivityInfos ? item.mActivityInfo : null, flags);
dest.writeTypedObject(item.mTextLinks, flags);
@@ -1262,10 +1381,11 @@
CharSequence text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
String htmlText = in.readString8();
Intent intent = in.readTypedObject(Intent.CREATOR);
+ PendingIntent pendingIntent = in.readTypedObject(PendingIntent.CREATOR);
Uri uri = in.readTypedObject(Uri.CREATOR);
ActivityInfo info = in.readTypedObject(ActivityInfo.CREATOR);
TextLinks textLinks = in.readTypedObject(TextLinks.CREATOR);
- Item item = new Item(text, htmlText, intent, uri);
+ Item item = new Item(text, htmlText, intent, pendingIntent, uri);
item.setActivityInfo(info);
item.setTextLinks(textLinks);
mItems.add(item);
@@ -1273,7 +1393,7 @@
}
public static final @android.annotation.NonNull Parcelable.Creator<ClipData> CREATOR =
- new Parcelable.Creator<ClipData>() {
+ new Parcelable.Creator<>() {
@Override
public ClipData createFromParcel(Parcel source) {
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 08871d4..333c363 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -19,6 +19,7 @@
import static android.app.sdksandbox.SdkSandboxManager.ACTION_START_SANDBOXED_ACTIVITY;
import static android.content.ContentProvider.maybeAddUserId;
import static android.os.Flags.FLAG_ALLOW_PRIVATE_PROFILE;
+import static android.service.chooser.Flags.FLAG_ENABLE_SHARESHEET_METADATA_EXTRA;
import android.Manifest;
import android.accessibilityservice.AccessibilityService;
@@ -6156,6 +6157,17 @@
public static final String EXTRA_INITIAL_INTENTS = "android.intent.extra.INITIAL_INTENTS";
/**
+ * A CharSequence of additional text describing the content being shared. This text will be
+ * displayed to the user as a part of the sharesheet when included in an
+ * {@link #ACTION_CHOOSER} {@link Intent}.
+ *
+ * <p>e.g. When sharing a photo, metadata could inform the user that location data is included
+ * in the photo they are sharing.</p>
+ */
+ @FlaggedApi(FLAG_ENABLE_SHARESHEET_METADATA_EXTRA)
+ public static final String EXTRA_METADATA_TEXT = "android.intent.extra.METADATA_TEXT";
+
+ /**
* A {@link IntentSender} to start after instant app installation success.
* @hide
*/
diff --git a/core/java/android/content/IntentFilter.java b/core/java/android/content/IntentFilter.java
index 79af65a..d913581 100644
--- a/core/java/android/content/IntentFilter.java
+++ b/core/java/android/content/IntentFilter.java
@@ -559,6 +559,10 @@
sb.append(" sch=");
sb.append(mDataSchemes.toString());
}
+ if (Flags.relativeReferenceIntentFilters() && countUriRelativeFilterGroups() > 0) {
+ sb.append(" grp=");
+ sb.append(mUriRelativeFilterGroups.toString());
+ }
sb.append(" }");
return sb.toString();
}
@@ -1807,13 +1811,7 @@
if (mUriRelativeFilterGroups == null) {
return false;
}
- for (int i = 0; i < mUriRelativeFilterGroups.size(); i++) {
- UriRelativeFilterGroup group = mUriRelativeFilterGroups.get(i);
- if (group.matchData(data)) {
- return group.getAction() == UriRelativeFilterGroup.ACTION_ALLOW;
- }
- }
- return false;
+ return UriRelativeFilterGroup.matchGroupsToUri(mUriRelativeFilterGroups, data);
}
/**
diff --git a/core/java/android/content/UriRelativeFilter.java b/core/java/android/content/UriRelativeFilter.java
index 9866cd0..6d33246 100644
--- a/core/java/android/content/UriRelativeFilter.java
+++ b/core/java/android/content/UriRelativeFilter.java
@@ -217,6 +217,15 @@
+ " }";
}
+ /** @hide */
+ public UriRelativeFilterParcel toParcel() {
+ UriRelativeFilterParcel parcel = new UriRelativeFilterParcel();
+ parcel.uriPart = mUriPart;
+ parcel.patternType = mPatternType;
+ parcel.filter = mFilter;
+ return parcel;
+ }
+
@Override
public boolean equals(@Nullable Object o) {
if (this == o) return true;
@@ -257,4 +266,11 @@
mPatternType = Integer.parseInt(parser.getAttributeValue(null, PATTERN_STR));
mFilter = parser.getAttributeValue(null, FILTER_STR);
}
+
+ /** @hide */
+ public UriRelativeFilter(UriRelativeFilterParcel parcel) {
+ mUriPart = parcel.uriPart;
+ mPatternType = parcel.patternType;
+ mFilter = parcel.filter;
+ }
}
diff --git a/core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl b/core/java/android/content/UriRelativeFilterGroup.aidl
similarity index 81%
rename from core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl
rename to core/java/android/content/UriRelativeFilterGroup.aidl
index 838e41e..b251054 100644
--- a/core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl
+++ b/core/java/android/content/UriRelativeFilterGroup.aidl
@@ -14,11 +14,6 @@
* limitations under the License.
*/
-package android.hardware;
+package android.content;
-/** @hide */
-parcelable CameraPrivacyAllowlistEntry {
- String packageName;
- boolean isMandatory;
-}
-
+parcelable UriRelativeFilterGroup;
diff --git a/core/java/android/content/UriRelativeFilterGroup.java b/core/java/android/content/UriRelativeFilterGroup.java
index 72c396a..0e49b4f 100644
--- a/core/java/android/content/UriRelativeFilterGroup.java
+++ b/core/java/android/content/UriRelativeFilterGroup.java
@@ -19,6 +19,7 @@
import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.content.pm.Flags;
import android.net.Uri;
import android.os.Parcel;
@@ -36,9 +37,11 @@
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
+import java.util.List;
import java.util.Objects;
/**
@@ -83,6 +86,40 @@
private final @Action int mAction;
private final ArraySet<UriRelativeFilter> mUriRelativeFilters = new ArraySet<>();
+ /** @hide */
+ public static boolean matchGroupsToUri(List<UriRelativeFilterGroup> groups, Uri uri) {
+ for (int i = 0; i < groups.size(); i++) {
+ if (groups.get(i).matchData(uri)) {
+ return groups.get(i).getAction() == UriRelativeFilterGroup.ACTION_ALLOW;
+ }
+ }
+ return false;
+ }
+
+ /** @hide */
+ public static List<UriRelativeFilterGroup> parcelsToGroups(
+ @Nullable List<UriRelativeFilterGroupParcel> parcels) {
+ List<UriRelativeFilterGroup> groups = new ArrayList<>();
+ if (parcels != null) {
+ for (int i = 0; i < parcels.size(); i++) {
+ groups.add(new UriRelativeFilterGroup(parcels.get(i)));
+ }
+ }
+ return groups;
+ }
+
+ /** @hide */
+ public static List<UriRelativeFilterGroupParcel> groupsToParcels(
+ @Nullable List<UriRelativeFilterGroup> groups) {
+ List<UriRelativeFilterGroupParcel> parcels = new ArrayList<>();
+ if (groups != null) {
+ for (int i = 0; i < groups.size(); i++) {
+ parcels.add(groups.get(i).toParcel());
+ }
+ }
+ return parcels;
+ }
+
/**
* New UriRelativeFilterGroup that matches a Intent data.
*
@@ -205,6 +242,35 @@
}
}
+ @Override
+ public boolean equals(@Nullable Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ @SuppressWarnings("unchecked")
+ UriRelativeFilterGroup that = (UriRelativeFilterGroup) o;
+ if (mAction != that.mAction) return false;
+ return mUriRelativeFilters.equals(that.mUriRelativeFilters);
+ }
+
+ @Override
+ public int hashCode() {
+ int _hash = 0;
+ _hash = 31 * _hash + mAction;
+ _hash = 31 * _hash + java.util.Objects.hashCode(mUriRelativeFilters);
+ return _hash;
+ }
+
+ /** @hide */
+ public UriRelativeFilterGroupParcel toParcel() {
+ UriRelativeFilterGroupParcel parcel = new UriRelativeFilterGroupParcel();
+ parcel.action = mAction;
+ parcel.filters = new ArrayList<>();
+ for (UriRelativeFilter filter : mUriRelativeFilters) {
+ parcel.filters.add(filter.toParcel());
+ }
+ return parcel;
+ }
+
/** @hide */
UriRelativeFilterGroup(@NonNull Parcel src) {
mAction = src.readInt();
@@ -213,4 +279,12 @@
mUriRelativeFilters.add(new UriRelativeFilter(src));
}
}
+
+ /** @hide */
+ public UriRelativeFilterGroup(UriRelativeFilterGroupParcel parcel) {
+ mAction = parcel.action;
+ for (int i = 0; i < parcel.filters.size(); i++) {
+ mUriRelativeFilters.add(new UriRelativeFilter(parcel.filters.get(i)));
+ }
+ }
}
diff --git a/core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl b/core/java/android/content/UriRelativeFilterGroupParcel.aidl
similarity index 71%
copy from core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl
copy to core/java/android/content/UriRelativeFilterGroupParcel.aidl
index 838e41e..3679e7f 100644
--- a/core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl
+++ b/core/java/android/content/UriRelativeFilterGroupParcel.aidl
@@ -14,11 +14,15 @@
* limitations under the License.
*/
-package android.hardware;
+package android.content;
-/** @hide */
-parcelable CameraPrivacyAllowlistEntry {
- String packageName;
- boolean isMandatory;
+import android.content.UriRelativeFilterParcel;
+
+/**
+ * Class for holding UriRelativeFilterGroup data.
+ * @hide
+ */
+parcelable UriRelativeFilterGroupParcel {
+ int action;
+ List<UriRelativeFilterParcel> filters;
}
-
diff --git a/core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl b/core/java/android/content/UriRelativeFilterParcel.aidl
similarity index 64%
copy from core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl
copy to core/java/android/content/UriRelativeFilterParcel.aidl
index 838e41e..4fb196d 100644
--- a/core/java/android/hardware/CameraPrivacyAllowlistEntry.aidl
+++ b/core/java/android/content/UriRelativeFilterParcel.aidl
@@ -1,11 +1,11 @@
-/**
- * Copyright (c) 2024, The Android Open Source Project
+/*
+ * Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,11 +14,14 @@
* limitations under the License.
*/
-package android.hardware;
+package android.content;
-/** @hide */
-parcelable CameraPrivacyAllowlistEntry {
- String packageName;
- boolean isMandatory;
+/**
+ * Class for holding UriRelativeFilter data.
+ * @hide
+ */
+parcelable UriRelativeFilterParcel {
+ int uriPart;
+ int patternType;
+ String filter;
}
-
diff --git a/core/java/android/content/pm/ServiceInfo.java b/core/java/android/content/pm/ServiceInfo.java
index 2b378b1..5b0cee7 100644
--- a/core/java/android/content/pm/ServiceInfo.java
+++ b/core/java/android/content/pm/ServiceInfo.java
@@ -142,6 +142,28 @@
* the {@link android.R.attr#foregroundServiceType} attribute.
* Data(photo, file, account) upload/download, backup/restore, import/export, fetch,
* transfer over network between device and cloud.
+ *
+ * <p>This type has time limit of 6 hours starting from Android version
+ * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}.
+ * A foreground service of this type must be stopped within the timeout by
+ * {@link android.app.Service#stopSelf()},
+ * {@link android.content.Context#stopService(android.content.Intent)} or their overloads).
+ * {@link android.app.Service#stopForeground(int)} will also work, which will demote the
+ * service to a "background" service, which will soon be stopped by the system.
+ *
+ * <p>If the service isn't stopped within the timeout,
+ * {@link android.app.Service#onTimeout(int, int)} will be called.
+ *
+ * <p>Also note, even though
+ * {@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_DATA_SYNC} can be used on
+ * Android versions prior to {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, since
+ * {@link android.app.Service#onTimeout(int, int)} did not exist on such versions, it will
+ * never be called.
+ *
+ * Because of this, developers must make sure to stop the foreground service even if
+ * {@link android.app.Service#onTimeout(int, int)} is not called on such versions.
+ *
+ * @see android.app.Service#onTimeout(int, int)
*/
@RequiresPermission(
value = Manifest.permission.FOREGROUND_SERVICE_DATA_SYNC,
@@ -483,6 +505,27 @@
* Constant corresponding to {@code mediaProcessing} in
* the {@link android.R.attr#foregroundServiceType} attribute.
* Media processing use cases such as video or photo editing and processing.
+ *
+ * This type has time limit of 6 hours.
+ * A foreground service of this type must be stopped within the timeout by
+ * {@link android.app.Service#stopSelf()},
+ * {@link android.content.Context#stopService(android.content.Intent)} or their overloads).
+ * {@link android.app.Service#stopForeground(int)} will also work, which will demote the
+ * service to a "background" service, which will soon be stopped by the system.
+ *
+ * <p>If the service isn't stopped within the timeout,
+ * {@link android.app.Service#onTimeout(int, int)} will be called.
+ *
+ * <p>Also note, even though
+ * {@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING} was added in
+ * Android version {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, it can be also used
+ * on prior android versions (just like other new foreground service types can be used).
+ * However, because {@link android.app.Service#onTimeout(int, int)} did not exist on prior
+ * versions, it will never be called on such versions.
+ * Because of this, developers must make sure to stop the foreground service even if
+ * {@link android.app.Service#onTimeout(int, int)} is not called on such versions.
+ *
+ * @see android.app.Service#onTimeout(int, int)
*/
@RequiresPermission(
value = Manifest.permission.FOREGROUND_SERVICE_MEDIA_PROCESSING
diff --git a/core/java/android/content/pm/verify/domain/DomainVerificationManager.java b/core/java/android/content/pm/verify/domain/DomainVerificationManager.java
index 77bd147..4dcc517 100644
--- a/core/java/android/content/pm/verify/domain/DomainVerificationManager.java
+++ b/core/java/android/content/pm/verify/domain/DomainVerificationManager.java
@@ -17,6 +17,7 @@
package android.content.pm.verify.domain;
import android.annotation.CheckResult;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -25,15 +26,21 @@
import android.annotation.SystemService;
import android.content.Context;
import android.content.Intent;
+import android.content.UriRelativeFilterGroup;
+import android.content.UriRelativeFilterGroupParcel;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.os.Bundle;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
import android.os.UserHandle;
+import android.util.ArrayMap;
import com.android.internal.util.CollectionUtils;
+import java.util.Collections;
import java.util.Comparator;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
@@ -156,6 +163,74 @@
}
/**
+ * Update the URI relative filter groups for a package. All previously existing groups
+ * will be cleared before the new groups will be applied.
+ *
+ * @param packageName The name of the package.
+ * @param domainToGroupsMap A map of domains to a list of {@link UriRelativeFilterGroup}s that
+ * should apply to them. Groups for each domain will replace any groups
+ * provided for that domain in a prior call to this method. Groups will
+ * be evaluated in the order they are provided.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.DOMAIN_VERIFICATION_AGENT)
+ @FlaggedApi(android.content.pm.Flags.FLAG_RELATIVE_REFERENCE_INTENT_FILTERS)
+ public void setUriRelativeFilterGroups(@NonNull String packageName,
+ @NonNull Map<String, List<UriRelativeFilterGroup>> domainToGroupsMap) {
+ Objects.requireNonNull(packageName);
+ Objects.requireNonNull(domainToGroupsMap);
+ Bundle bundle = new Bundle();
+ for (String domain : domainToGroupsMap.keySet()) {
+ List<UriRelativeFilterGroup> groups = domainToGroupsMap.get(domain);
+ bundle.putParcelableList(domain, UriRelativeFilterGroup.groupsToParcels(groups));
+ }
+ try {
+ mDomainVerificationManager.setUriRelativeFilterGroups(packageName, bundle);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Retrieves a map of a package's verified domains to a list of {@link UriRelativeFilterGroup}s
+ * that applies to them.
+ *
+ * @param packageName The name of the package.
+ * @param domains List of domains for which to retrieve group matches.
+ * @return A map of domains to the lists of {@link UriRelativeFilterGroup}s that apply to them.
+ * @hide
+ */
+ @NonNull
+ @SystemApi
+ @FlaggedApi(android.content.pm.Flags.FLAG_RELATIVE_REFERENCE_INTENT_FILTERS)
+ public Map<String, List<UriRelativeFilterGroup>> getUriRelativeFilterGroups(
+ @NonNull String packageName,
+ @NonNull List<String> domains) {
+ Objects.requireNonNull(packageName);
+ Objects.requireNonNull(domains);
+ if (domains.isEmpty()) {
+ return Collections.emptyMap();
+ }
+ try {
+ Bundle bundle = mDomainVerificationManager.getUriRelativeFilterGroups(packageName,
+ domains);
+ ArrayMap<String, List<UriRelativeFilterGroup>> map = new ArrayMap<>();
+ if (!bundle.isEmpty()) {
+ for (String domain : bundle.keySet()) {
+ List<UriRelativeFilterGroupParcel> parcels =
+ bundle.getParcelableArrayList(domain,
+ UriRelativeFilterGroupParcel.class);
+ map.put(domain, UriRelativeFilterGroup.parcelsToGroups(parcels));
+ }
+ }
+ return map;
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Used to iterate all {@link DomainVerificationInfo} values to do cleanup or retries. This is
* usually a heavy workload and should be done infrequently.
*
diff --git a/core/java/android/content/pm/verify/domain/IDomainVerificationManager.aidl b/core/java/android/content/pm/verify/domain/IDomainVerificationManager.aidl
index 53205f3..f5af82d 100644
--- a/core/java/android/content/pm/verify/domain/IDomainVerificationManager.aidl
+++ b/core/java/android/content/pm/verify/domain/IDomainVerificationManager.aidl
@@ -20,6 +20,8 @@
import android.content.pm.verify.domain.DomainSet;
import android.content.pm.verify.domain.DomainVerificationInfo;
import android.content.pm.verify.domain.DomainVerificationUserState;
+import android.content.UriRelativeFilterGroup;
+import android.os.Bundle;
import java.util.List;
/**
@@ -46,4 +48,8 @@
int setDomainVerificationUserSelection(String domainSetId, in DomainSet domains,
boolean enabled, int userId);
+
+ void setUriRelativeFilterGroups(String packageName, in Bundle domainToGroupsBundle);
+
+ Bundle getUriRelativeFilterGroups(String packageName, in List<String> domains);
}
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 23b9d0b..d259e97 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -137,6 +137,8 @@
private ArrayList<ApkAssets> mUserApkAssets = new ArrayList<>();
private ArrayList<ResourcesLoader> mLoaders = new ArrayList<>();
+ private boolean mNoInit = false;
+
public Builder addApkAssets(ApkAssets apkAssets) {
mUserApkAssets.add(apkAssets);
return this;
@@ -147,6 +149,11 @@
return this;
}
+ public Builder setNoInit() {
+ mNoInit = true;
+ return this;
+ }
+
public AssetManager build() {
// Retrieving the system ApkAssets forces their creation as well.
final ApkAssets[] systemApkAssets = getSystem().getApkAssets();
@@ -188,7 +195,7 @@
final AssetManager assetManager = new AssetManager(false /*sentinel*/);
assetManager.mApkAssets = apkAssets;
AssetManager.nativeSetApkAssets(assetManager.mObject, apkAssets,
- false /*invalidateCaches*/);
+ false /*invalidateCaches*/, mNoInit /*preset*/);
assetManager.mLoaders = mLoaders.isEmpty() ? null
: mLoaders.toArray(new ResourcesLoader[0]);
@@ -329,7 +336,7 @@
synchronized (this) {
ensureOpenLocked();
mApkAssets = newApkAssets;
- nativeSetApkAssets(mObject, mApkAssets, invalidateCaches);
+ nativeSetApkAssets(mObject, mApkAssets, invalidateCaches, false);
if (invalidateCaches) {
// Invalidate all caches.
invalidateCachesLocked(-1);
@@ -496,7 +503,7 @@
mApkAssets = Arrays.copyOf(mApkAssets, count + 1);
mApkAssets[count] = assets;
- nativeSetApkAssets(mObject, mApkAssets, true);
+ nativeSetApkAssets(mObject, mApkAssets, true, false);
invalidateCachesLocked(-1);
return count + 1;
}
@@ -1503,12 +1510,29 @@
int navigation, int screenWidth, int screenHeight, int smallestScreenWidthDp,
int screenWidthDp, int screenHeightDp, int screenLayout, int uiMode, int colorMode,
int grammaticalGender, int majorVersion) {
+ setConfigurationInternal(mcc, mnc, defaultLocale, locales, orientation,
+ touchscreen, density, keyboard, keyboardHidden, navigation, screenWidth,
+ screenHeight, smallestScreenWidthDp, screenWidthDp, screenHeightDp,
+ screenLayout, uiMode, colorMode, grammaticalGender, majorVersion, false);
+ }
+
+ /**
+ * Change the configuration used when retrieving resources, and potentially force a refresh of
+ * the state. Not for use by applications.
+ * @hide
+ */
+ void setConfigurationInternal(int mcc, int mnc, String defaultLocale, String[] locales,
+ int orientation, int touchscreen, int density, int keyboard, int keyboardHidden,
+ int navigation, int screenWidth, int screenHeight, int smallestScreenWidthDp,
+ int screenWidthDp, int screenHeightDp, int screenLayout, int uiMode, int colorMode,
+ int grammaticalGender, int majorVersion, boolean forceRefresh) {
synchronized (this) {
ensureValidLocked();
nativeSetConfiguration(mObject, mcc, mnc, defaultLocale, locales, orientation,
touchscreen, density, keyboard, keyboardHidden, navigation, screenWidth,
screenHeight, smallestScreenWidthDp, screenWidthDp, screenHeightDp,
- screenLayout, uiMode, colorMode, grammaticalGender, majorVersion);
+ screenLayout, uiMode, colorMode, grammaticalGender, majorVersion,
+ forceRefresh);
}
}
@@ -1593,13 +1617,13 @@
private static native long nativeCreate();
private static native void nativeDestroy(long ptr);
private static native void nativeSetApkAssets(long ptr, @NonNull ApkAssets[] apkAssets,
- boolean invalidateCaches);
+ boolean invalidateCaches, boolean preset);
private static native void nativeSetConfiguration(long ptr, int mcc, int mnc,
@Nullable String defaultLocale, @NonNull String[] locales, int orientation,
int touchscreen, int density, int keyboard, int keyboardHidden, int navigation,
int screenWidth, int screenHeight, int smallestScreenWidthDp, int screenWidthDp,
int screenHeightDp, int screenLayout, int uiMode, int colorMode, int grammaticalGender,
- int majorVersion);
+ int majorVersion, boolean forceRefresh);
private static native @NonNull SparseArray<String> nativeGetAssignedPackageIdentifiers(
long ptr, boolean includeOverlays, boolean includeLoaders);
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index 5e442b8..079c2c1 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -200,7 +200,7 @@
mMetrics.setToDefaults();
mDisplayAdjustments = displayAdjustments;
mConfiguration.setToDefaults();
- updateConfiguration(config, metrics, displayAdjustments.getCompatibilityInfo());
+ updateConfigurationImpl(config, metrics, displayAdjustments.getCompatibilityInfo(), true);
}
public DisplayAdjustments getDisplayAdjustments() {
@@ -402,7 +402,12 @@
}
public void updateConfiguration(Configuration config, DisplayMetrics metrics,
- CompatibilityInfo compat) {
+ CompatibilityInfo compat) {
+ updateConfigurationImpl(config, metrics, compat, false);
+ }
+
+ private void updateConfigurationImpl(Configuration config, DisplayMetrics metrics,
+ CompatibilityInfo compat, boolean forceAssetsRefresh) {
Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "ResourcesImpl#updateConfiguration");
try {
synchronized (mAccessLock) {
@@ -528,7 +533,7 @@
keyboardHidden = mConfiguration.keyboardHidden;
}
- mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
+ mAssets.setConfigurationInternal(mConfiguration.mcc, mConfiguration.mnc,
defaultLocale,
selectedLocales,
mConfiguration.orientation,
@@ -539,7 +544,7 @@
mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
mConfiguration.screenLayout, mConfiguration.uiMode,
mConfiguration.colorMode, mConfiguration.getGrammaticalGender(),
- Build.VERSION.RESOURCES_SDK_INT);
+ Build.VERSION.RESOURCES_SDK_INT, forceAssetsRefresh);
if (DEBUG_CONFIG) {
Slog.i(TAG, "**** Updating config of " + this + ": final config is "
diff --git a/core/java/android/hardware/ISensorPrivacyListener.aidl b/core/java/android/hardware/ISensorPrivacyListener.aidl
index 19ae302..2ac21d2 100644
--- a/core/java/android/hardware/ISensorPrivacyListener.aidl
+++ b/core/java/android/hardware/ISensorPrivacyListener.aidl
@@ -25,6 +25,5 @@
// frameworks/native/libs/sensorprivacy/aidl/android/hardware/ISensorPrivacyListener.aidl
// =============== Beginning of transactions used on native side as well ======================
void onSensorPrivacyChanged(int toggleType, int sensor, boolean enabled);
- void onSensorPrivacyStateChanged(int toggleType, int sensor, int state);
// =============== End of transactions used on native side as well ============================
}
diff --git a/core/java/android/hardware/ISensorPrivacyManager.aidl b/core/java/android/hardware/ISensorPrivacyManager.aidl
index 851ce2a..9cf329c 100644
--- a/core/java/android/hardware/ISensorPrivacyManager.aidl
+++ b/core/java/android/hardware/ISensorPrivacyManager.aidl
@@ -16,7 +16,6 @@
package android.hardware;
-import android.hardware.CameraPrivacyAllowlistEntry;
import android.hardware.ISensorPrivacyListener;
/** @hide */
@@ -46,22 +45,6 @@
void setToggleSensorPrivacy(int userId, int source, int sensor, boolean enable);
void setToggleSensorPrivacyForProfileGroup(int userId, int source, int sensor, boolean enable);
-
- @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY)")
- List<CameraPrivacyAllowlistEntry> getCameraPrivacyAllowlist();
-
- @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY)")
- int getToggleSensorPrivacyState(int toggleType, int sensor);
-
- @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.MANAGE_SENSOR_PRIVACY)")
- void setToggleSensorPrivacyState(int userId, int source, int sensor, int state);
-
- @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.MANAGE_SENSOR_PRIVACY)")
- void setToggleSensorPrivacyStateForProfileGroup(int userId, int source, int sensor, int state);
-
- @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY)")
- boolean isCameraPrivacyEnabled(String packageName);
-
// =============== End of transactions used on native side as well ============================
void suppressToggleSensorPrivacyReminders(int userId, int sensor, IBinder token,
@@ -70,4 +53,4 @@
boolean requiresAuthentication();
void showSensorUseDialog(int sensor);
-}
+}
\ No newline at end of file
diff --git a/core/java/android/hardware/SensorPrivacyManager.java b/core/java/android/hardware/SensorPrivacyManager.java
index 4c0a4b9..18c95bfb 100644
--- a/core/java/android/hardware/SensorPrivacyManager.java
+++ b/core/java/android/hardware/SensorPrivacyManager.java
@@ -17,7 +17,6 @@
package android.hardware;
import android.Manifest;
-import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
@@ -39,11 +38,9 @@
import android.util.Pair;
import com.android.internal.annotations.GuardedBy;
-import com.android.internal.camera.flags.Flags;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
@@ -218,41 +215,13 @@
public static final int DISABLED = SensorPrivacyIndividualEnabledSensorProto.DISABLED;
/**
- * Constant indicating privacy is enabled except for the automotive driver assistance apps
- * which are helpful for driving.
- */
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public static final int AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS =
- SensorPrivacyIndividualEnabledSensorProto.AUTO_DRIVER_ASSISTANCE_HELPFUL_APPS;
-
- /**
- * Constant indicating privacy is enabled except for the automotive driver assistance apps
- * which are required by car manufacturer for driving.
- */
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public static final int AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS =
- SensorPrivacyIndividualEnabledSensorProto.AUTO_DRIVER_ASSISTANCE_REQUIRED_APPS;
-
- /**
- * Constant indicating privacy is enabled except for the automotive driver assistance apps
- * which are both helpful for driving and also apps required by car manufacturer for
- * driving.
- */
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public static final int AUTOMOTIVE_DRIVER_ASSISTANCE_APPS =
- SensorPrivacyIndividualEnabledSensorProto.AUTO_DRIVER_ASSISTANCE_APPS;
-
- /**
* Types of state which can exist for a sensor privacy toggle
*
* @hide
*/
@IntDef(value = {
ENABLED,
- DISABLED,
- AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS,
- AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS,
- AUTOMOTIVE_DRIVER_ASSISTANCE_APPS
+ DISABLED
})
@Retention(RetentionPolicy.SOURCE)
public @interface StateType {}
@@ -297,19 +266,6 @@
private int mToggleType;
private int mSensor;
private boolean mEnabled;
- private int mState;
-
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private SensorPrivacyChangedParams(int toggleType, int sensor, int state) {
- mToggleType = toggleType;
- mSensor = sensor;
- mState = state;
- if (state == StateTypes.ENABLED) {
- mEnabled = true;
- } else {
- mEnabled = false;
- }
- }
private SensorPrivacyChangedParams(int toggleType, int sensor, boolean enabled) {
mToggleType = toggleType;
@@ -328,12 +284,6 @@
public boolean isEnabled() {
return mEnabled;
}
-
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public @StateTypes.StateType int getState() {
- return mState;
- }
-
}
}
@@ -369,9 +319,6 @@
private final ArrayMap<Pair<Integer, OnSensorPrivacyChangedListener>,
OnSensorPrivacyChangedListener> mLegacyToggleListeners = new ArrayMap<>();
- @GuardedBy("mLock")
- private ArrayMap<String, Boolean> mCameraPrivacyAllowlist = null;
-
/** The singleton ISensorPrivacyListener for IPC which will be used to dispatch to local
* listeners */
@NonNull
@@ -381,33 +328,12 @@
synchronized (mLock) {
for (int i = 0; i < mToggleListeners.size(); i++) {
OnSensorPrivacyChangedListener listener = mToggleListeners.keyAt(i);
- if (Flags.privacyAllowlist()) {
- int state = enabled ? StateTypes.ENABLED : StateTypes.DISABLED;
- mToggleListeners.valueAt(i).execute(() -> listener
- .onSensorPrivacyChanged(new OnSensorPrivacyChangedListener
- .SensorPrivacyChangedParams(toggleType, sensor, state)));
- } else {
- mToggleListeners.valueAt(i).execute(() -> listener
- .onSensorPrivacyChanged(new OnSensorPrivacyChangedListener
- .SensorPrivacyChangedParams(toggleType, sensor, enabled)));
- }
- }
- }
- }
-
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public void onSensorPrivacyStateChanged(int toggleType, int sensor, int state) {
- synchronized (mLock) {
- for (int i = 0; i < mToggleListeners.size(); i++) {
- OnSensorPrivacyChangedListener listener = mToggleListeners.keyAt(i);
mToggleListeners.valueAt(i).execute(() -> listener
.onSensorPrivacyChanged(new OnSensorPrivacyChangedListener
- .SensorPrivacyChangedParams(toggleType, sensor, state)));
+ .SensorPrivacyChangedParams(toggleType, sensor, enabled)));
}
}
}
-
};
/** Whether the singleton ISensorPrivacyListener has been registered */
@@ -723,73 +649,6 @@
}
/**
- * Returns sensor privacy state for a specific sensor.
- *
- * @return int sensor privacy state.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public @StateTypes.StateType int getSensorPrivacyState(@ToggleType int toggleType,
- @Sensors.Sensor int sensor) {
- try {
- return mService.getToggleSensorPrivacyState(toggleType, sensor);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns if camera privacy is enabled for a specific package.
- *
- * @return boolean sensor privacy state.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public boolean isCameraPrivacyEnabled(@NonNull String packageName) {
- try {
- return mService.isCameraPrivacyEnabled(packageName);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns camera privacy allowlist.
- *
- * @return List of automotive driver assistance packages for
- * privacy allowlisting. The returned map includes the package
- * name as key and the value is a Boolean which tells if that package
- * is required by the car manufacturer as mandatory package for driving.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public @NonNull Map<String, Boolean> getCameraPrivacyAllowlist() {
- synchronized (mLock) {
- if (mCameraPrivacyAllowlist == null) {
- mCameraPrivacyAllowlist = new ArrayMap<>();
- try {
- for (CameraPrivacyAllowlistEntry entry :
- mService.getCameraPrivacyAllowlist()) {
- mCameraPrivacyAllowlist.put(entry.packageName, entry.isMandatory);
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- return mCameraPrivacyAllowlist;
- }
- }
-
- /**
* Sets sensor privacy to the specified state for an individual sensor.
*
* @param sensor the sensor which to change the state for
@@ -818,22 +677,6 @@
* Sets sensor privacy to the specified state for an individual sensor.
*
* @param sensor the sensor which to change the state for
- * @param state the state to which sensor privacy should be set.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public void setSensorPrivacyState(@Sensors.Sensor int sensor,
- @StateTypes.StateType int state) {
- setSensorPrivacyState(resolveSourceFromCurrentContext(), sensor, state);
- }
-
- /**
- * Sets sensor privacy to the specified state for an individual sensor.
- *
- * @param sensor the sensor which to change the state for
* @param enable the state to which sensor privacy should be set.
*
* @hide
@@ -865,27 +708,6 @@
}
/**
- * Sets sensor privacy to the specified state for an individual sensor.
- *
- * @param sensor the sensor which to change the state for
- * @param state the state to which sensor privacy should be set.
- *
- * @hide
- */
- @TestApi
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public void setSensorPrivacyState(@Sources.Source int source, @Sensors.Sensor int sensor,
- @StateTypes.StateType int state) {
- try {
- mService.setToggleSensorPrivacyState(mContext.getUserId(), source, sensor, state);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- }
-
- /**
* Sets sensor privacy to the specified state for an individual sensor for the profile group of
* context's user.
*
@@ -923,28 +745,6 @@
}
/**
- * Sets sensor privacy to the specified state for an individual sensor for the profile group of
- * context's user.
- *
- * @param source the source using which the sensor is toggled.
- * @param sensor the sensor which to change the state for
- * @param state the state to which sensor privacy should be set.
- *
- * @hide
- */
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public void setSensorPrivacyStateForProfileGroup(@Sources.Source int source,
- @Sensors.Sensor int sensor, @StateTypes.StateType int state) {
- try {
- mService.setToggleSensorPrivacyStateForProfileGroup(mContext.getUserId(), source,
- sensor, state);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
* Don't show dialogs to turn off sensor privacy for this package.
*
* @param suppress Whether to suppress or re-enable.
@@ -1065,12 +865,6 @@
boolean enabled) {
listener.onAllSensorPrivacyChanged(enabled);
}
-
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public void onSensorPrivacyStateChanged(int toggleType, int sensor,
- int state) {
- }
};
mListeners.put(listener, iListener);
}
diff --git a/core/java/android/hardware/biometrics/BiometricPrompt.java b/core/java/android/hardware/biometrics/BiometricPrompt.java
index bdaf9d7..d4c58b2 100644
--- a/core/java/android/hardware/biometrics/BiometricPrompt.java
+++ b/core/java/android/hardware/biometrics/BiometricPrompt.java
@@ -200,6 +200,25 @@
return this;
}
+ /**
+ * Optional: Sets logo description text that will be shown on the prompt.
+ *
+ * <p> Note that using this method is not recommended in most scenarios because the calling
+ * application's name will be used by default. Setting the logo description is intended for
+ * large bundled applications that perform a wide range of functions and need to show
+ * distinct description for each function.
+ *
+ * @param logoDescription The logo description text that will be shown on the prompt.
+ * @return This builder.
+ */
+ @FlaggedApi(FLAG_CUSTOM_BIOMETRIC_PROMPT)
+ @RequiresPermission(SET_BIOMETRIC_DIALOG_LOGO)
+ @NonNull
+ public BiometricPrompt.Builder setLogoDescription(@NonNull String logoDescription) {
+ mPromptInfo.setLogoDescription(logoDescription);
+ return this;
+ }
+
/**
* Required: Sets the title that will be shown on the prompt.
@@ -743,7 +762,20 @@
return mPromptInfo.getLogoBitmap();
}
-
+ /**
+ * Gets the logo description for the prompt, as set by
+ * {@link Builder#setDescription(CharSequence)}.
+ * Currently for system applications use only.
+ *
+ * @return The logo description of the prompt, or null if the prompt has no logo description
+ * set.
+ */
+ @FlaggedApi(FLAG_CUSTOM_BIOMETRIC_PROMPT)
+ @RequiresPermission(SET_BIOMETRIC_DIALOG_LOGO)
+ @Nullable
+ public String getLogoDescription() {
+ return mPromptInfo.getLogoDescription();
+ }
/**
* Gets the title for the prompt, as set by {@link Builder#setTitle(CharSequence)}.
diff --git a/core/java/android/hardware/biometrics/PromptInfo.java b/core/java/android/hardware/biometrics/PromptInfo.java
index 0f9cadc..2236660 100644
--- a/core/java/android/hardware/biometrics/PromptInfo.java
+++ b/core/java/android/hardware/biometrics/PromptInfo.java
@@ -34,6 +34,7 @@
@DrawableRes private int mLogoRes = -1;
@Nullable private Bitmap mLogoBitmap;
+ @Nullable private String mLogoDescription;
@NonNull private CharSequence mTitle;
private boolean mUseDefaultTitle;
@Nullable private CharSequence mSubtitle;
@@ -62,6 +63,7 @@
PromptInfo(Parcel in) {
mLogoRes = in.readInt();
mLogoBitmap = in.readTypedObject(Bitmap.CREATOR);
+ mLogoDescription = in.readString();
mTitle = in.readCharSequence();
mUseDefaultTitle = in.readBoolean();
mSubtitle = in.readCharSequence();
@@ -106,6 +108,7 @@
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mLogoRes);
dest.writeTypedObject(mLogoBitmap, 0);
+ dest.writeString(mLogoDescription);
dest.writeCharSequence(mTitle);
dest.writeBoolean(mUseDefaultTitle);
dest.writeCharSequence(mSubtitle);
@@ -173,6 +176,8 @@
return true;
} else if (mLogoBitmap != null) {
return true;
+ } else if (mLogoDescription != null) {
+ return true;
}
return false;
}
@@ -189,6 +194,10 @@
checkOnlyOneLogoSet();
}
+ public void setLogoDescription(@NonNull String logoDescription) {
+ mLogoDescription = logoDescription;
+ }
+
public void setTitle(CharSequence title) {
mTitle = title;
}
@@ -282,6 +291,10 @@
return mLogoBitmap;
}
+ public String getLogoDescription() {
+ return mLogoDescription;
+ }
+
public CharSequence getTitle() {
return mTitle;
}
diff --git a/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java b/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java
index 7abe821..3b10e0d 100644
--- a/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraExtensionCharacteristics.java
@@ -19,7 +19,9 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.SuppressLint;
import android.content.ComponentName;
+import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
@@ -40,6 +42,7 @@
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemProperties;
+import android.provider.Settings;
import android.util.IntArray;
import android.util.Log;
import android.util.Pair;
@@ -53,6 +56,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -243,16 +247,19 @@
private static final String PROXY_SERVICE_NAME =
"com.android.cameraextensions.CameraExtensionsProxyService";
+ @FlaggedApi(Flags.FLAG_CONCERT_MODE)
+ private static final int FALLBACK_PACKAGE_NAME =
+ com.android.internal.R.string.config_extensionFallbackPackageName;
+ @FlaggedApi(Flags.FLAG_CONCERT_MODE)
+ private static final int FALLBACK_SERVICE_NAME =
+ com.android.internal.R.string.config_extensionFallbackServiceName;
+
// Singleton instance
private static final CameraExtensionManagerGlobal GLOBAL_CAMERA_MANAGER =
new CameraExtensionManagerGlobal();
private final Object mLock = new Object();
private final int PROXY_SERVICE_DELAY_MS = 2000;
- private InitializerFuture mInitFuture = null;
- private ServiceConnection mConnection = null;
- private int mConnectionCount = 0;
- private ICameraExtensionsProxyService mProxy = null;
- private boolean mSupportsAdvancedExtensions = false;
+ private ExtensionConnectionManager mConnectionManager = new ExtensionConnectionManager();
// Singleton, don't allow construction
private CameraExtensionManagerGlobal() {}
@@ -261,17 +268,17 @@
return GLOBAL_CAMERA_MANAGER;
}
- private void releaseProxyConnectionLocked(Context ctx) {
- if (mConnection != null ) {
- ctx.unbindService(mConnection);
- mConnection = null;
- mProxy = null;
- mConnectionCount = 0;
+ private void releaseProxyConnectionLocked(Context ctx, int extension) {
+ if (mConnectionManager.getConnection(extension) != null) {
+ ctx.unbindService(mConnectionManager.getConnection(extension));
+ mConnectionManager.setConnection(extension, null);
+ mConnectionManager.setProxy(extension, null);
+ mConnectionManager.resetConnectionCount(extension);
}
}
- private void connectToProxyLocked(Context ctx) {
- if (mConnection == null) {
+ private void connectToProxyLocked(Context ctx, int extension, boolean useFallback) {
+ if (mConnectionManager.getConnection(extension) == null) {
Intent intent = new Intent();
intent.setClassName(PROXY_PACKAGE_NAME, PROXY_SERVICE_NAME);
String vendorProxyPackage = SystemProperties.get(
@@ -287,34 +294,55 @@
+ vendorProxyService);
intent.setClassName(vendorProxyPackage, vendorProxyService);
}
- mInitFuture = new InitializerFuture();
- mConnection = new ServiceConnection() {
+
+ if (Flags.concertMode() && useFallback) {
+ String packageName = ctx.getResources().getString(FALLBACK_PACKAGE_NAME);
+ String serviceName = ctx.getResources().getString(FALLBACK_SERVICE_NAME);
+
+ if (!packageName.isEmpty() && !serviceName.isEmpty()) {
+ Log.v(TAG,
+ "Choosing the fallback software implementation package: "
+ + packageName);
+ Log.v(TAG,
+ "Choosing the fallback software implementation service: "
+ + serviceName);
+ intent.setClassName(packageName, serviceName);
+ }
+ }
+
+ InitializerFuture initFuture = new InitializerFuture();
+ ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName component) {
- mConnection = null;
- mProxy = null;
+ mConnectionManager.setConnection(extension, null);
+ mConnectionManager.setProxy(extension, null);
}
@Override
public void onServiceConnected(ComponentName component, IBinder binder) {
- mProxy = ICameraExtensionsProxyService.Stub.asInterface(binder);
- if (mProxy == null) {
+ ICameraExtensionsProxyService proxy =
+ ICameraExtensionsProxyService.Stub.asInterface(binder);
+ mConnectionManager.setProxy(extension, proxy);
+ if (mConnectionManager.getProxy(extension) == null) {
throw new IllegalStateException("Camera Proxy service is null");
}
try {
- mSupportsAdvancedExtensions = mProxy.advancedExtensionsSupported();
+ mConnectionManager.setAdvancedExtensionsSupported(extension,
+ mConnectionManager.getProxy(extension)
+ .advancedExtensionsSupported());
} catch (RemoteException e) {
Log.e(TAG, "Remote IPC failed!");
}
- mInitFuture.setStatus(true);
+ initFuture.setStatus(true);
}
};
ctx.bindService(intent, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT |
Context.BIND_ABOVE_CLIENT | Context.BIND_NOT_VISIBLE,
- android.os.AsyncTask.THREAD_POOL_EXECUTOR, mConnection);
+ android.os.AsyncTask.THREAD_POOL_EXECUTOR, connection);
+ mConnectionManager.setConnection(extension, connection);
try {
- mInitFuture.get(PROXY_SERVICE_DELAY_MS, TimeUnit.MILLISECONDS);
+ initFuture.get(PROXY_SERVICE_DELAY_MS, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
Log.e(TAG, "Timed out while initializing proxy service!");
}
@@ -366,64 +394,102 @@
}
}
- public boolean registerClient(Context ctx, IBinder token) {
+ public boolean registerClientHelper(Context ctx, IBinder token, int extension,
+ boolean useFallback) {
synchronized (mLock) {
boolean ret = false;
- connectToProxyLocked(ctx);
- if (mProxy == null) {
+ connectToProxyLocked(ctx, extension, useFallback);
+ if (mConnectionManager.getProxy(extension) == null) {
return false;
}
- mConnectionCount++;
+ mConnectionManager.incrementConnectionCount(extension);
try {
- ret = mProxy.registerClient(token);
+ ret = mConnectionManager.getProxy(extension).registerClient(token);
} catch (RemoteException e) {
Log.e(TAG, "Failed to initialize extension! Extension service does "
+ " not respond!");
}
if (!ret) {
- mConnectionCount--;
+ mConnectionManager.decrementConnectionCount(extension);
}
- if (mConnectionCount <= 0) {
- releaseProxyConnectionLocked(ctx);
+ if (mConnectionManager.getConnectionCount(extension) <= 0) {
+ releaseProxyConnectionLocked(ctx, extension);
}
return ret;
}
}
- public void unregisterClient(Context ctx, IBinder token) {
+ @SuppressLint("NonUserGetterCalled")
+ public boolean registerClient(Context ctx, IBinder token, int extension,
+ String cameraId, Map<String, CameraMetadataNative> characteristicsMapNative) {
+ boolean ret = registerClientHelper(ctx, token, extension, false /*useFallback*/);
+
+ if (Flags.concertMode()) {
+ // Check if user enabled fallback impl
+ ContentResolver resolver = ctx.getContentResolver();
+ int userEnabled = Settings.Secure.getInt(resolver,
+ Settings.Secure.CAMERA_EXTENSIONS_FALLBACK, 1);
+
+ boolean vendorImpl = true;
+ if (ret && (mConnectionManager.getProxy(extension) != null) && (userEnabled == 1)) {
+ // At this point, we are connected to either CameraExtensionsProxyService or
+ // the vendor extension proxy service. If the vendor does not support the
+ // extension, unregisterClient and re-register client with the proxy service
+ // containing the fallback impl
+ vendorImpl = isExtensionSupported(cameraId, extension,
+ characteristicsMapNative);
+ }
+
+ if (!vendorImpl) {
+ unregisterClient(ctx, token, extension);
+ ret = registerClientHelper(ctx, token, extension, true /*useFallback*/);
+
+ }
+ }
+
+ return ret;
+ }
+
+ public void unregisterClient(Context ctx, IBinder token, int extension) {
synchronized (mLock) {
- if (mProxy != null) {
+ if (mConnectionManager.getProxy(extension) != null) {
try {
- mProxy.unregisterClient(token);
+ mConnectionManager.getProxy(extension).unregisterClient(token);
} catch (RemoteException e) {
Log.e(TAG, "Failed to de-initialize extension! Extension service does"
+ " not respond!");
} finally {
- mConnectionCount--;
- if (mConnectionCount <= 0) {
- releaseProxyConnectionLocked(ctx);
+ mConnectionManager.decrementConnectionCount(extension);
+ if (mConnectionManager.getConnectionCount(extension) <= 0) {
+ releaseProxyConnectionLocked(ctx, extension);
}
}
}
}
}
- public void initializeSession(IInitializeSessionCallback cb) throws RemoteException {
+ public void initializeSession(IInitializeSessionCallback cb, int extension)
+ throws RemoteException {
synchronized (mLock) {
- if (mProxy != null) {
- mProxy.initializeSession(cb);
+ if (mConnectionManager.getProxy(extension) != null
+ && !mConnectionManager.isSessionInitialized()) {
+ mConnectionManager.getProxy(extension).initializeSession(cb);
+ mConnectionManager.setSessionInitialized(true);
+ } else {
+ cb.onFailure();
}
}
}
- public void releaseSession() {
+ public void releaseSession(int extension) {
synchronized (mLock) {
- if (mProxy != null) {
+ if (mConnectionManager.getProxy(extension) != null) {
try {
- mProxy.releaseSession();
+ mConnectionManager.getProxy(extension).releaseSession();
+ mConnectionManager.setSessionInitialized(false);
} catch (RemoteException e) {
Log.e(TAG, "Failed to release session! Extension service does"
+ " not respond!");
@@ -432,77 +498,157 @@
}
}
- public boolean areAdvancedExtensionsSupported() {
- return mSupportsAdvancedExtensions;
+ public boolean areAdvancedExtensionsSupported(int extension) {
+ return mConnectionManager.areAdvancedExtensionsSupported(extension);
}
- public IPreviewExtenderImpl initializePreviewExtension(int extensionType)
+ public IPreviewExtenderImpl initializePreviewExtension(int extension)
throws RemoteException {
synchronized (mLock) {
- if (mProxy != null) {
- return mProxy.initializePreviewExtension(extensionType);
+ if (mConnectionManager.getProxy(extension) != null) {
+ return mConnectionManager.getProxy(extension)
+ .initializePreviewExtension(extension);
} else {
return null;
}
}
}
- public IImageCaptureExtenderImpl initializeImageExtension(int extensionType)
+ public IImageCaptureExtenderImpl initializeImageExtension(int extension)
throws RemoteException {
synchronized (mLock) {
- if (mProxy != null) {
- return mProxy.initializeImageExtension(extensionType);
+ if (mConnectionManager.getProxy(extension) != null) {
+ return mConnectionManager.getProxy(extension)
+ .initializeImageExtension(extension);
} else {
return null;
}
}
}
- public IAdvancedExtenderImpl initializeAdvancedExtension(int extensionType)
+ public IAdvancedExtenderImpl initializeAdvancedExtension(int extension)
throws RemoteException {
synchronized (mLock) {
- if (mProxy != null) {
- return mProxy.initializeAdvancedExtension(extensionType);
+ if (mConnectionManager.getProxy(extension) != null) {
+ return mConnectionManager.getProxy(extension)
+ .initializeAdvancedExtension(extension);
} else {
return null;
}
}
}
+
+ private class ExtensionConnectionManager {
+ // Maps extension to ExtensionConnection
+ private Map<Integer, ExtensionConnection> mConnections = new HashMap<>();
+ private boolean mSessionInitialized = false;
+
+ public ExtensionConnectionManager() {
+ IntArray extensionList = new IntArray(EXTENSION_LIST.length);
+ extensionList.addAll(EXTENSION_LIST);
+ if (Flags.concertMode()) {
+ extensionList.add(EXTENSION_EYES_FREE_VIDEOGRAPHY);
+ }
+
+ for (int extensionType : extensionList.toArray()) {
+ mConnections.put(extensionType, new ExtensionConnection());
+ }
+ }
+
+ public ICameraExtensionsProxyService getProxy(@Extension int extension) {
+ return mConnections.get(extension).mProxy;
+ }
+
+ public ServiceConnection getConnection(@Extension int extension) {
+ return mConnections.get(extension).mConnection;
+ }
+
+ public int getConnectionCount(@Extension int extension) {
+ return mConnections.get(extension).mConnectionCount;
+ }
+
+ public boolean areAdvancedExtensionsSupported(@Extension int extension) {
+ return mConnections.get(extension).mSupportsAdvancedExtensions;
+ }
+
+ public boolean isSessionInitialized() {
+ return mSessionInitialized;
+ }
+
+ public void setProxy(@Extension int extension, ICameraExtensionsProxyService proxy) {
+ mConnections.get(extension).mProxy = proxy;
+ }
+
+ public void setConnection(@Extension int extension, ServiceConnection connection) {
+ mConnections.get(extension).mConnection = connection;
+ }
+
+ public void incrementConnectionCount(@Extension int extension) {
+ mConnections.get(extension).mConnectionCount++;
+ }
+
+ public void decrementConnectionCount(@Extension int extension) {
+ mConnections.get(extension).mConnectionCount--;
+ }
+
+ public void resetConnectionCount(@Extension int extension) {
+ mConnections.get(extension).mConnectionCount = 0;
+ }
+
+ public void setAdvancedExtensionsSupported(@Extension int extension,
+ boolean advancedExtSupported) {
+ mConnections.get(extension).mSupportsAdvancedExtensions = advancedExtSupported;
+ }
+
+ public void setSessionInitialized(boolean initialized) {
+ mSessionInitialized = initialized;
+ }
+
+ private class ExtensionConnection {
+ public ICameraExtensionsProxyService mProxy = null;
+ public ServiceConnection mConnection = null;
+ public int mConnectionCount = 0;
+ public boolean mSupportsAdvancedExtensions = false;
+ }
+ }
}
/**
* @hide
*/
- public static boolean registerClient(Context ctx, IBinder token) {
- return CameraExtensionManagerGlobal.get().registerClient(ctx, token);
+ public static boolean registerClient(Context ctx, IBinder token, int extension,
+ String cameraId, Map<String, CameraMetadataNative> characteristicsMapNative) {
+ return CameraExtensionManagerGlobal.get().registerClient(ctx, token, extension, cameraId,
+ characteristicsMapNative);
}
/**
* @hide
*/
- public static void unregisterClient(Context ctx, IBinder token) {
- CameraExtensionManagerGlobal.get().unregisterClient(ctx, token);
+ public static void unregisterClient(Context ctx, IBinder token, int extension) {
+ CameraExtensionManagerGlobal.get().unregisterClient(ctx, token, extension);
}
/**
* @hide
*/
- public static void initializeSession(IInitializeSessionCallback cb) throws RemoteException {
- CameraExtensionManagerGlobal.get().initializeSession(cb);
+ public static void initializeSession(IInitializeSessionCallback cb, int extension)
+ throws RemoteException {
+ CameraExtensionManagerGlobal.get().initializeSession(cb, extension);
}
/**
* @hide
*/
- public static void releaseSession() {
- CameraExtensionManagerGlobal.get().releaseSession();
+ public static void releaseSession(int extension) {
+ CameraExtensionManagerGlobal.get().releaseSession(extension);
}
/**
* @hide
*/
- public static boolean areAdvancedExtensionsSupported() {
- return CameraExtensionManagerGlobal.get().areAdvancedExtensionsSupported();
+ public static boolean areAdvancedExtensionsSupported(int extension) {
+ return CameraExtensionManagerGlobal.get().areAdvancedExtensionsSupported(extension);
}
/**
@@ -510,7 +656,7 @@
*/
public static boolean isExtensionSupported(String cameraId, int extensionType,
Map<String, CameraMetadataNative> characteristicsMap) {
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extensionType)) {
try {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extensionType);
return extender.isExtensionAvailable(cameraId, characteristicsMap);
@@ -600,24 +746,24 @@
public @NonNull List<Integer> getSupportedExtensions() {
ArrayList<Integer> ret = new ArrayList<>();
final IBinder token = new Binder(TAG + "#getSupportedExtensions:" + mCameraId);
- boolean success = registerClient(mContext, token);
- if (!success) {
- return Collections.unmodifiableList(ret);
- }
IntArray extensionList = new IntArray(EXTENSION_LIST.length);
extensionList.addAll(EXTENSION_LIST);
if (Flags.concertMode()) {
extensionList.add(EXTENSION_EYES_FREE_VIDEOGRAPHY);
}
- try {
- for (int extensionType : extensionList.toArray()) {
- if (isExtensionSupported(mCameraId, extensionType, mCharacteristicsMapNative)) {
+
+ for (int extensionType : extensionList.toArray()) {
+ try {
+ boolean success = registerClient(mContext, token, extensionType, mCameraId,
+ mCharacteristicsMapNative);
+ if (success && isExtensionSupported(mCameraId, extensionType,
+ mCharacteristicsMapNative)) {
ret.add(extensionType);
}
+ } finally {
+ unregisterClient(mContext, token, extensionType);
}
- } finally {
- unregisterClient(mContext, token);
}
return Collections.unmodifiableList(ret);
@@ -643,7 +789,8 @@
public <T> @Nullable T get(@Extension int extension,
@NonNull CameraCharacteristics.Key<T> key) {
final IBinder token = new Binder(TAG + "#get:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -653,7 +800,7 @@
throw new IllegalArgumentException("Unsupported extension");
}
- if (areAdvancedExtensionsSupported() && getKeys(extension).contains(key)) {
+ if (areAdvancedExtensionsSupported(extension) && getKeys(extension).contains(key)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
CameraMetadataNative metadata =
@@ -670,7 +817,7 @@
Log.e(TAG, "Failed to query the extension for the specified key! Extension "
+ "service does not respond!");
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
return null;
}
@@ -691,7 +838,8 @@
public @NonNull Set<CameraCharacteristics.Key> getKeys(@Extension int extension) {
final IBinder token =
new Binder(TAG + "#getKeys:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -703,7 +851,7 @@
throw new IllegalArgumentException("Unsupported extension");
}
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
CameraMetadataNative metadata =
@@ -732,7 +880,7 @@
Log.e(TAG, "Failed to query the extension for all available keys! Extension "
+ "service does not respond!");
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
return Collections.unmodifiableSet(ret);
}
@@ -755,7 +903,8 @@
*/
public boolean isPostviewAvailable(@Extension int extension) {
final IBinder token = new Binder(TAG + "#isPostviewAvailable:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -765,7 +914,7 @@
throw new IllegalArgumentException("Unsupported extension");
}
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
return extender.isPostviewAvailable();
@@ -779,7 +928,7 @@
Log.e(TAG, "Failed to query the extension for postview availability! Extension "
+ "service does not respond!");
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
return false;
@@ -813,7 +962,8 @@
public List<Size> getPostviewSupportedSizes(@Extension int extension,
@NonNull Size captureSize, int format) {
final IBinder token = new Binder(TAG + "#getPostviewSupportedSizes:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -831,7 +981,7 @@
StreamConfigurationMap streamMap = mCharacteristicsMap.get(mCameraId).get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
switch(format) {
case ImageFormat.YUV_420_888:
case ImageFormat.JPEG:
@@ -879,7 +1029,7 @@
+ "service does not respond!");
return Collections.emptyList();
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
}
@@ -917,7 +1067,8 @@
// ambiguity is resolved in b/169799538.
final IBinder token = new Binder(TAG + "#getExtensionSupportedSizes:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -929,7 +1080,7 @@
StreamConfigurationMap streamMap = mCharacteristicsMap.get(mCameraId).get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
return generateSupportedSizes(
@@ -948,7 +1099,7 @@
+ " not respond!");
return new ArrayList<>();
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
}
@@ -978,7 +1129,8 @@
List<Size> getExtensionSupportedSizes(@Extension int extension, int format) {
try {
final IBinder token = new Binder(TAG + "#getExtensionSupportedSizes:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -990,7 +1142,7 @@
StreamConfigurationMap streamMap = mCharacteristicsMap.get(mCameraId).get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
switch(format) {
case ImageFormat.YUV_420_888:
case ImageFormat.JPEG:
@@ -1035,7 +1187,7 @@
}
}
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
} catch (RemoteException e) {
Log.e(TAG, "Failed to query the extension supported sizes! Extension service does"
@@ -1073,7 +1225,8 @@
}
final IBinder token = new Binder(TAG + "#getEstimatedCaptureLatencyRangeMillis:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -1087,7 +1240,7 @@
new android.hardware.camera2.extension.Size();
sz.width = captureOutputSize.getWidth();
sz.height = captureOutputSize.getHeight();
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
LatencyRange latencyRange = extender.getEstimatedCaptureLatencyRange(mCameraId,
@@ -1126,7 +1279,7 @@
Log.e(TAG, "Failed to query the extension capture latency! Extension service does"
+ " not respond!");
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
return null;
@@ -1143,7 +1296,8 @@
*/
public boolean isCaptureProcessProgressAvailable(@Extension int extension) {
final IBinder token = new Binder(TAG + "#isCaptureProcessProgressAvailable:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -1153,7 +1307,7 @@
throw new IllegalArgumentException("Unsupported extension");
}
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
return extender.isCaptureProcessProgressAvailable();
@@ -1167,7 +1321,7 @@
Log.e(TAG, "Failed to query the extension progress callbacks! Extension service does"
+ " not respond!");
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
return false;
@@ -1195,7 +1349,8 @@
@NonNull
public Set<CaptureRequest.Key> getAvailableCaptureRequestKeys(@Extension int extension) {
final IBinder token = new Binder(TAG + "#getAvailableCaptureRequestKeys:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -1208,7 +1363,7 @@
}
CameraMetadataNative captureRequestMeta = null;
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
captureRequestMeta = extender.getAvailableCaptureRequestKeys(mCameraId);
@@ -1250,7 +1405,7 @@
} catch (RemoteException e) {
throw new IllegalStateException("Failed to query the available capture request keys!");
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
return Collections.unmodifiableSet(ret);
@@ -1282,7 +1437,8 @@
@NonNull
public Set<CaptureResult.Key> getAvailableCaptureResultKeys(@Extension int extension) {
final IBinder token = new Binder(TAG + "#getAvailableCaptureResultKeys:" + mCameraId);
- boolean success = registerClient(mContext, token);
+ boolean success = registerClient(mContext, token, extension, mCameraId,
+ mCharacteristicsMapNative);
if (!success) {
throw new IllegalArgumentException("Unsupported extensions");
}
@@ -1294,7 +1450,7 @@
}
CameraMetadataNative captureResultMeta = null;
- if (areAdvancedExtensionsSupported()) {
+ if (areAdvancedExtensionsSupported(extension)) {
IAdvancedExtenderImpl extender = initializeAdvancedExtension(extension);
extender.init(mCameraId, mCharacteristicsMapNative);
captureResultMeta = extender.getAvailableCaptureResultKeys(mCameraId);
@@ -1336,7 +1492,7 @@
} catch (RemoteException e) {
throw new IllegalStateException("Failed to query the available capture result keys!");
} finally {
- unregisterClient(mContext, token);
+ unregisterClient(mContext, token, extension);
}
return Collections.unmodifiableSet(ret);
diff --git a/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
index f6c8f36..b2032fa 100644
--- a/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
@@ -102,6 +102,8 @@
private boolean mInitialized;
private boolean mSessionClosed;
+ private int mExtensionType;
+
private final Context mContext;
@@ -205,7 +207,7 @@
CameraAdvancedExtensionSessionImpl ret = new CameraAdvancedExtensionSessionImpl(ctx,
extender, cameraDevice, characteristicsMapNative, repeatingRequestSurface,
burstCaptureSurface, postviewSurface, config.getStateCallback(),
- config.getExecutor(), sessionId, token);
+ config.getExecutor(), sessionId, token, config.getExtension());
ret.mStatsAggregator.setClientName(ctx.getOpPackageName());
ret.mStatsAggregator.setExtensionType(config.getExtension());
@@ -223,7 +225,8 @@
@Nullable Surface postviewSurface,
@NonNull StateCallback callback, @NonNull Executor executor,
int sessionId,
- @NonNull IBinder token) {
+ @NonNull IBinder token,
+ int extension) {
mContext = ctx;
mAdvancedExtender = extender;
mCameraDevice = cameraDevice;
@@ -242,6 +245,7 @@
mSessionId = sessionId;
mToken = token;
mInterfaceLock = cameraDevice.mInterfaceLock;
+ mExtensionType = extension;
mStatsAggregator = new ExtensionSessionStatsAggregator(mCameraDevice.getId(),
/*isAdvanced=*/true);
@@ -583,9 +587,9 @@
if (mToken != null) {
if (mInitialized || (mCaptureSession != null)) {
notifyClose = true;
- CameraExtensionCharacteristics.releaseSession();
+ CameraExtensionCharacteristics.releaseSession(mExtensionType);
}
- CameraExtensionCharacteristics.unregisterClient(mContext, mToken);
+ CameraExtensionCharacteristics.unregisterClient(mContext, mToken, mExtensionType);
}
mInitialized = false;
mToken = null;
@@ -654,7 +658,8 @@
}
try {
- CameraExtensionCharacteristics.initializeSession(mInitializeHandler);
+ CameraExtensionCharacteristics.initializeSession(
+ mInitializeHandler, mExtensionType);
} catch (RemoteException e) {
Log.e(TAG, "Failed to initialize session! Extension service does"
+ " not respond!");
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index ccb24e7..f03876b 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -2559,13 +2559,16 @@
boolean initializationFailed = true;
IBinder token = new Binder(TAG + " : " + mNextSessionId++);
try {
- boolean ret = CameraExtensionCharacteristics.registerClient(mContext, token);
+ boolean ret = CameraExtensionCharacteristics.registerClient(mContext, token,
+ extensionConfiguration.getExtension(), mCameraId,
+ CameraExtensionUtils.getCharacteristicsMapNative(characteristicsMap));
if (!ret) {
token = null;
throw new UnsupportedOperationException("Unsupported extension!");
}
- if (CameraExtensionCharacteristics.areAdvancedExtensionsSupported()) {
+ if (CameraExtensionCharacteristics.areAdvancedExtensionsSupported(
+ extensionConfiguration.getExtension())) {
mCurrentAdvancedExtensionSession =
CameraAdvancedExtensionSessionImpl.createCameraAdvancedExtensionSession(
this, characteristicsMap, mContext, extensionConfiguration,
@@ -2580,7 +2583,8 @@
throw new CameraAccessException(CameraAccessException.CAMERA_ERROR);
} finally {
if (initializationFailed && (token != null)) {
- CameraExtensionCharacteristics.unregisterClient(mContext, token);
+ CameraExtensionCharacteristics.unregisterClient(mContext, token,
+ extensionConfiguration.getExtension());
}
}
}
diff --git a/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
index db7055b..725b413 100644
--- a/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
@@ -118,6 +118,7 @@
// In case the client doesn't explicitly enable repeating requests, the framework
// will do so internally.
private boolean mInternalRepeatingRequestEnabled = true;
+ private int mExtensionType;
private final Context mContext;
@@ -244,7 +245,8 @@
sessionId,
token,
extensionChars.getAvailableCaptureRequestKeys(config.getExtension()),
- extensionChars.getAvailableCaptureResultKeys(config.getExtension()));
+ extensionChars.getAvailableCaptureResultKeys(config.getExtension()),
+ config.getExtension());
session.mStatsAggregator.setClientName(ctx.getOpPackageName());
session.mStatsAggregator.setExtensionType(config.getExtension());
@@ -266,7 +268,8 @@
int sessionId,
@NonNull IBinder token,
@NonNull Set<CaptureRequest.Key> requestKeys,
- @Nullable Set<CaptureResult.Key> resultKeys) {
+ @Nullable Set<CaptureResult.Key> resultKeys,
+ int extension) {
mContext = ctx;
mImageExtender = imageExtender;
mPreviewExtender = previewExtender;
@@ -289,6 +292,7 @@
mSupportedResultKeys = resultKeys;
mCaptureResultsSupported = !resultKeys.isEmpty();
mInterfaceLock = cameraDevice.mInterfaceLock;
+ mExtensionType = extension;
mStatsAggregator = new ExtensionSessionStatsAggregator(mCameraDevice.getId(),
/*isAdvanced=*/false);
@@ -881,9 +885,9 @@
if (mToken != null) {
if (mInitialized || (mCaptureSession != null)) {
notifyClose = true;
- CameraExtensionCharacteristics.releaseSession();
+ CameraExtensionCharacteristics.releaseSession(mExtensionType);
}
- CameraExtensionCharacteristics.unregisterClient(mContext, mToken);
+ CameraExtensionCharacteristics.unregisterClient(mContext, mToken, mExtensionType);
}
mInitialized = false;
mToken = null;
@@ -1000,7 +1004,8 @@
mStatsAggregator.commit(/*isFinal*/false);
try {
finishPipelineInitialization();
- CameraExtensionCharacteristics.initializeSession(mInitializeHandler);
+ CameraExtensionCharacteristics.initializeSession(
+ mInitializeHandler, mExtensionType);
} catch (RemoteException e) {
Log.e(TAG, "Failed to initialize session! Extension service does"
+ " not respond!");
diff --git a/services/core/java/com/android/server/devicestate/DeviceState.java b/core/java/android/hardware/devicestate/DeviceState.java
similarity index 96%
rename from services/core/java/com/android/server/devicestate/DeviceState.java
rename to core/java/android/hardware/devicestate/DeviceState.java
index 2ba59b0..5a34905 100644
--- a/services/core/java/com/android/server/devicestate/DeviceState.java
+++ b/core/java/android/hardware/devicestate/DeviceState.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.devicestate;
+package android.hardware.devicestate;
import static android.hardware.devicestate.DeviceStateManager.MAXIMUM_DEVICE_STATE;
import static android.hardware.devicestate.DeviceStateManager.MINIMUM_DEVICE_STATE;
@@ -22,7 +22,6 @@
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
-import android.hardware.devicestate.DeviceStateManager;
import com.android.internal.util.Preconditions;
@@ -38,9 +37,9 @@
* state of the system. This is useful for variable-state devices, like foldable or rollable
* devices, that can be configured by users into differing hardware states, which each may have a
* different expected use case.
+ * @hide
*
- * @see DeviceStateProvider
- * @see DeviceStateManagerService
+ * @see DeviceStateManager
*/
public final class DeviceState {
/**
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 0fbdbc4..de32423 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -180,11 +180,14 @@
/**
- * User type representing a private profile.
+ * User type representing a private profile. Private profile is a user profile that can be used
+ * as an alternative user-space to install and use sensitive apps.
+ * UI surfaces can adopt an alternative strategy to show apps belonging to this profile, in line
+ * with their sensitive nature.
* @hide
*/
@FlaggedApi(android.os.Flags.FLAG_ALLOW_PRIVATE_PROFILE)
- @TestApi
+ @SystemApi
public static final String USER_TYPE_PROFILE_PRIVATE = "android.os.usertype.profile.PRIVATE";
/**
@@ -1424,8 +1427,8 @@
public static final String DISALLOW_RECORD_AUDIO = "no_record_audio";
/**
- * Specifies if a user is not allowed to run in the background and should be stopped during
- * user switch. The default value is <code>false</code>.
+ * Specifies if a user is not allowed to run in the background and should be stopped and locked
+ * during user switch. The default value is <code>false</code>.
*
* <p>This restriction can be set by device owners and profile owners.
*
diff --git a/core/java/android/provider/BlockedNumberContract.java b/core/java/android/provider/BlockedNumberContract.java
index 5d00b29..4075e90 100644
--- a/core/java/android/provider/BlockedNumberContract.java
+++ b/core/java/android/provider/BlockedNumberContract.java
@@ -15,12 +15,20 @@
*/
package android.provider;
+import android.Manifest;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
+import android.annotation.SystemApi;
import android.annotation.WorkerThread;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.telecom.Log;
+import android.telecom.TelecomManager;
+
+import com.android.server.telecom.flags.Flags;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -214,6 +222,333 @@
* <p>TYPE: String</p>
*/
public static final String COLUMN_E164_NUMBER = "e164_number";
+
+ /**
+ * A protected broadcast intent action for letting components with
+ * {@link android.Manifest.permission#READ_BLOCKED_NUMBERS} know that the block suppression
+ * status as returned by {@link #getBlockSuppressionStatus(Context)} has been updated.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final String ACTION_BLOCK_SUPPRESSION_STATE_CHANGED =
+ "android.provider.action.BLOCK_SUPPRESSION_STATE_CHANGED";
+
+ /**
+ * Preference key of block numbers not in contacts setting.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final String ENHANCED_SETTING_KEY_BLOCK_UNREGISTERED =
+ "block_numbers_not_in_contacts_setting";
+
+ /**
+ * Preference key of block private number calls setting.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final String ENHANCED_SETTING_KEY_BLOCK_PRIVATE =
+ "block_private_number_calls_setting";
+
+ /**
+ * Preference key of block payphone calls setting.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final String ENHANCED_SETTING_KEY_BLOCK_PAYPHONE =
+ "block_payphone_calls_setting";
+
+ /**
+ * Preference key of block unknown calls setting.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final String ENHANCED_SETTING_KEY_BLOCK_UNKNOWN =
+ "block_unknown_calls_setting";
+
+ /**
+ * Preference key for whether should show an emergency call notification.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final String ENHANCED_SETTING_KEY_SHOW_EMERGENCY_CALL_NOTIFICATION =
+ "show_emergency_call_notification";
+
+ /**
+ * Preference key of block unavailable calls setting.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final String ENHANCED_SETTING_KEY_BLOCK_UNAVAILABLE =
+ "block_unavailable_calls_setting";
+
+ /**
+ * Notifies the provider that emergency services were contacted by the user.
+ * <p> This results in {@link #shouldSystemBlockNumber} returning {@code false} independent
+ * of the contents of the provider for a duration defined by
+ * {@link android.telephony.CarrierConfigManager#KEY_DURATION_BLOCKING_DISABLED_AFTER_EMERGENCY_INT}
+ * the provider unless {@link #endBlockSuppression(Context)} is called.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.READ_BLOCKED_NUMBERS,
+ android.Manifest.permission.WRITE_BLOCKED_NUMBERS
+ })
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static void notifyEmergencyContact(@NonNull Context context) {
+ verifyBlockedNumbersPermission(context);
+ try {
+ Log.i(LOG_TAG, "notifyEmergencyContact; caller=%s", context.getOpPackageName());
+ context.getContentResolver().call(
+ AUTHORITY_URI, SystemContract.METHOD_NOTIFY_EMERGENCY_CONTACT, null, null);
+ } catch (NullPointerException | IllegalArgumentException ex) {
+ // The content resolver can throw an NPE or IAE; we don't want to crash Telecom if
+ // either of these happen.
+ Log.w(null, "notifyEmergencyContact: provider not ready.");
+ }
+ }
+
+ /**
+ * Notifies the provider to disable suppressing blocking. If emergency services were not
+ * contacted recently at all, calling this method is a no-op.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.READ_BLOCKED_NUMBERS,
+ android.Manifest.permission.WRITE_BLOCKED_NUMBERS
+ })
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static void endBlockSuppression(@NonNull Context context) {
+ verifyBlockedNumbersPermission(context);
+ String caller = context.getOpPackageName();
+ Log.i(LOG_TAG, "endBlockSuppression: caller=%s", caller);
+ context.getContentResolver().call(
+ AUTHORITY_URI, SystemContract.METHOD_END_BLOCK_SUPPRESSION, null, null);
+ }
+
+ /**
+ * Returns {@code true} if {@code phoneNumber} is blocked taking
+ * {@link #notifyEmergencyContact(Context)} into consideration. If emergency services
+ * have not been contacted recently and enhanced call blocking not been enabled, this
+ * method is equivalent to {@link #isBlocked(Context, String)}.
+ *
+ * @param context the context of the caller.
+ * @param phoneNumber the number to check.
+ * @param numberPresentation the presentation code associated with the call.
+ * @param isNumberInContacts indicates if the provided number exists as a contact.
+ * @return result code indicating if the number should be blocked, and if so why.
+ * Valid values are: {@link #STATUS_NOT_BLOCKED}, {@link #STATUS_BLOCKED_IN_LIST},
+ * {@link #STATUS_BLOCKED_NOT_IN_CONTACTS}, {@link #STATUS_BLOCKED_PAYPHONE},
+ * {@link #STATUS_BLOCKED_RESTRICTED}, {@link #STATUS_BLOCKED_UNKNOWN_NUMBER}.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.READ_BLOCKED_NUMBERS,
+ android.Manifest.permission.WRITE_BLOCKED_NUMBERS
+ })
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static int shouldSystemBlockNumber(@NonNull Context context,
+ @NonNull String phoneNumber, @TelecomManager.Presentation int numberPresentation,
+ boolean isNumberInContacts) {
+ verifyBlockedNumbersPermission(context);
+ try {
+ String caller = context.getOpPackageName();
+ Bundle extras = new Bundle();
+ extras.putInt(BlockedNumberContract.EXTRA_CALL_PRESENTATION, numberPresentation);
+ extras.putBoolean(BlockedNumberContract.EXTRA_CONTACT_EXIST, isNumberInContacts);
+ final Bundle res = context.getContentResolver().call(AUTHORITY_URI,
+ SystemContract.METHOD_SHOULD_SYSTEM_BLOCK_NUMBER, phoneNumber, extras);
+ int blockResult = res != null ? res.getInt(RES_BLOCK_STATUS, STATUS_NOT_BLOCKED) :
+ BlockedNumberContract.STATUS_NOT_BLOCKED;
+ Log.d(LOG_TAG, "shouldSystemBlockNumber: number=%s, caller=%s, result=%s",
+ Log.piiHandle(phoneNumber), caller,
+ SystemContract.blockStatusToString(blockResult));
+ return blockResult;
+ } catch (NullPointerException | IllegalArgumentException ex) {
+ // The content resolver can throw an NPE or IAE; we don't want to crash Telecom if
+ // either of these happen.
+ Log.w(null, "shouldSystemBlockNumber: provider not ready.");
+ return BlockedNumberContract.STATUS_NOT_BLOCKED;
+ }
+ }
+
+ /**
+ * Returns the current status of block suppression.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.READ_BLOCKED_NUMBERS,
+ android.Manifest.permission.WRITE_BLOCKED_NUMBERS
+ })
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static @NonNull BlockSuppressionStatus getBlockSuppressionStatus(
+ @NonNull Context context) {
+ verifyBlockedNumbersPermission(context);
+ final Bundle res = context.getContentResolver().call(
+ AUTHORITY_URI, SystemContract.METHOD_GET_BLOCK_SUPPRESSION_STATUS, null, null);
+ BlockSuppressionStatus blockSuppressionStatus = new BlockSuppressionStatus(
+ res.getBoolean(SystemContract.RES_IS_BLOCKING_SUPPRESSED, false),
+ res.getLong(SystemContract.RES_BLOCKING_SUPPRESSED_UNTIL_TIMESTAMP, 0));
+ Log.d(LOG_TAG, "getBlockSuppressionStatus: caller=%s, status=%s",
+ context.getOpPackageName(), blockSuppressionStatus);
+ return blockSuppressionStatus;
+ }
+
+ /**
+ * Check whether should show the emergency call notification.
+ *
+ * @param context the context of the caller.
+ * @return {@code true} if should show emergency call notification. {@code false} otherwise.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.READ_BLOCKED_NUMBERS,
+ android.Manifest.permission.WRITE_BLOCKED_NUMBERS
+ })
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static boolean shouldShowEmergencyCallNotification(@NonNull Context context) {
+ verifyBlockedNumbersPermission(context);
+ try {
+ final Bundle res = context.getContentResolver().call(AUTHORITY_URI,
+ SystemContract.METHOD_SHOULD_SHOW_EMERGENCY_CALL_NOTIFICATION, null, null);
+ return res != null && res.getBoolean(RES_SHOW_EMERGENCY_CALL_NOTIFICATION, false);
+ } catch (NullPointerException | IllegalArgumentException ex) {
+ // The content resolver can throw an NPE or IAE; we don't want to crash Telecom if
+ // either of these happen.
+ Log.w(null, "shouldShowEmergencyCallNotification: provider not ready.");
+ return false;
+ }
+ }
+
+ /**
+ * Check whether the enhanced block setting is enabled.
+ *
+ * @param context the context of the caller.
+ * @param key the key of the setting to check, can be
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_UNREGISTERED}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_PRIVATE}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_PAYPHONE}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_UNKNOWN}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_UNAVAILABLE}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_SHOW_EMERGENCY_CALL_NOTIFICATION}
+ * @return {@code true} if the setting is enabled. {@code false} otherwise.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.READ_BLOCKED_NUMBERS,
+ android.Manifest.permission.WRITE_BLOCKED_NUMBERS
+ })
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static boolean getBlockedNumberSetting(
+ @NonNull Context context, @NonNull String key) {
+ verifyBlockedNumbersPermission(context);
+ Bundle extras = new Bundle();
+ extras.putString(EXTRA_ENHANCED_SETTING_KEY, key);
+ try {
+ final Bundle res = context.getContentResolver().call(AUTHORITY_URI,
+ SystemContract.METHOD_GET_ENHANCED_BLOCK_SETTING, null, extras);
+ return res != null && res.getBoolean(RES_ENHANCED_SETTING_IS_ENABLED, false);
+ } catch (NullPointerException | IllegalArgumentException ex) {
+ // The content resolver can throw an NPE or IAE; we don't want to crash Telecom if
+ // either of these happen.
+ Log.w(null, "getEnhancedBlockSetting: provider not ready.");
+ return false;
+ }
+ }
+
+ /**
+ * Set the enhanced block setting enabled status.
+ *
+ * @param context the context of the caller.
+ * @param key the key of the setting to set, can be
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_UNREGISTERED}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_PRIVATE}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_PAYPHONE}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_UNKNOWN}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_BLOCK_UNAVAILABLE}
+ * {@link SystemContract#ENHANCED_SETTING_KEY_SHOW_EMERGENCY_CALL_NOTIFICATION}
+ * @param value the enabled statue of the setting to set.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.READ_BLOCKED_NUMBERS,
+ android.Manifest.permission.WRITE_BLOCKED_NUMBERS
+ })
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static void setBlockedNumberSetting(@NonNull Context context,
+ @NonNull String key, boolean value) {
+ verifyBlockedNumbersPermission(context);
+ Bundle extras = new Bundle();
+ extras.putString(EXTRA_ENHANCED_SETTING_KEY, key);
+ extras.putBoolean(EXTRA_ENHANCED_SETTING_VALUE, value);
+ context.getContentResolver().call(AUTHORITY_URI,
+ SystemContract.METHOD_SET_ENHANCED_BLOCK_SETTING, null, extras);
+ }
+
+ /**
+ * Represents the current status of
+ * {@link #shouldSystemBlockNumber(Context, String, int, boolean)}. If emergency services
+ * have been contacted recently, {@link #mIsSuppressed} is {@code true}, and blocking
+ * is disabled until the timestamp {@link #mUntilTimestampMillis}.
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
+ public static final class BlockSuppressionStatus {
+ private boolean mIsSuppressed;
+
+ /**
+ * Timestamp in milliseconds from epoch.
+ */
+ private long mUntilTimestampMillis;
+
+ public BlockSuppressionStatus(boolean isSuppressed, long untilTimestampMillis) {
+ this.mIsSuppressed = isSuppressed;
+ this.mUntilTimestampMillis = untilTimestampMillis;
+ }
+
+ @Override
+ public String toString() {
+ return "[BlockSuppressionStatus; isSuppressed=" + mIsSuppressed + ", until="
+ + mUntilTimestampMillis + "]";
+ }
+
+ public boolean getIsSuppressed() {
+ return mIsSuppressed;
+ }
+
+ public long getUntilTimestampMillis() {
+ return mUntilTimestampMillis;
+ }
+ }
+
+ /**
+ * Verifies that the caller holds both the
+ * {@link android.Manifest.permission#READ_BLOCKED_NUMBERS} permission and the
+ * {@link android.Manifest.permission#WRITE_BLOCKED_NUMBERS} permission.
+ *
+ * @param context
+ * @throws SecurityException if the caller is missing the necessary permissions
+ */
+ private static void verifyBlockedNumbersPermission(Context context) {
+ context.enforceCallingOrSelfPermission(Manifest.permission.READ_BLOCKED_NUMBERS,
+ "Caller does not have the android.permission.READ_BLOCKED_NUMBERS permission");
+ context.enforceCallingOrSelfPermission(Manifest.permission.WRITE_BLOCKED_NUMBERS,
+ "Caller does not have the android.permission.WRITE_BLOCKED_NUMBERS permission");
+ }
}
/** @hide */
@@ -558,7 +893,7 @@
* {@link #ENHANCED_SETTING_KEY_BLOCK_PAYPHONE}
* {@link #ENHANCED_SETTING_KEY_BLOCK_UNKNOWN}
* {@link #ENHANCED_SETTING_KEY_BLOCK_UNAVAILABLE}
- * {@link #ENHANCED_SETTING_KEY_EMERGENCY_CALL_NOTIFICATION_SHOWING}
+ * {@link #ENHANCED_SETTING_KEY_SHOW_EMERGENCY_CALL_NOTIFICATION}
* @return {@code true} if the setting is enabled. {@code false} otherwise.
*/
public static boolean getEnhancedBlockSetting(Context context, String key) {
@@ -586,7 +921,7 @@
* {@link #ENHANCED_SETTING_KEY_BLOCK_PAYPHONE}
* {@link #ENHANCED_SETTING_KEY_BLOCK_UNKNOWN}
* {@link #ENHANCED_SETTING_KEY_BLOCK_UNAVAILABLE}
- * {@link #ENHANCED_SETTING_KEY_EMERGENCY_CALL_NOTIFICATION_SHOWING}
+ * {@link #ENHANCED_SETTING_KEY_SHOW_EMERGENCY_CALL_NOTIFICATION}
* @param value the enabled statue of the setting to set.
*/
public static void setEnhancedBlockSetting(Context context, String key, boolean value) {
diff --git a/core/java/android/provider/ContactKeysManager.java b/core/java/android/provider/ContactKeysManager.java
index bef6456..01aaa3d 100644
--- a/core/java/android/provider/ContactKeysManager.java
+++ b/core/java/android/provider/ContactKeysManager.java
@@ -39,18 +39,19 @@
import java.util.Objects;
/**
- * ContactKeysManager provides the access to the E2EE contact keys provider.
- * It manages two types of keys - {@link ContactKey} of other users' and the owner's keys -
- * {@link SelfKey}.
+ * ContactKeysManager provides access to the provider of end-to-end encryption contact keys.
+ * It manages two types of keys - {@link ContactKey} and {@link SelfKey}.
* <ul>
* <li>
- * For {@link ContactKey} this API allows the insert/update, removal, changing of the
- * verification state, retrieving the keys (either created by or visible to the caller app)
- * operations.
+ * A {@link ContactKey} is a public key associated with a contact. It's used to end-to-end
+ * encrypt the communications between a user and the contact. This API allows operations on
+ * {@link ContactKey}s to insert/update, remove, change the verification state, and retrieving
+ * keys (either created by or visible to the caller app).
* </li>
* <li>
- * For {@link SelfKey} this API allows the insert/update, removal, retrieving the self keys
- * (either created by or visible to the caller app) operations.
+ * A {@link SelfKey} is a key for this device, so the key represents the owner of the device.
+ * This API allows operations on {@link SelfKey}s to insert/update, remove, and retrieving
+ * self keys (either created by or visible to the caller app).
* </li>
* </ul>
* Keys are uniquely identified by:
@@ -71,7 +72,7 @@
* ContactsProvider.
*/
@FlaggedApi(Flags.FLAG_USER_KEYS)
-public class ContactKeysManager {
+public final class ContactKeysManager {
/**
* The authority for the contact keys provider.
* @hide
@@ -354,9 +355,9 @@
private static void validateVerificationState(int verificationState) {
- if (verificationState != UNVERIFIED
- && verificationState != VERIFICATION_FAILED
- && verificationState != VERIFIED) {
+ if (verificationState != VERIFICATION_STATE_UNVERIFIED
+ && verificationState != VERIFICATION_STATE_VERIFICATION_FAILED
+ && verificationState != VERIFICATION_STATE_VERIFIED) {
throw new IllegalArgumentException("Verification state value "
+ verificationState + " is not supported");
}
@@ -600,25 +601,25 @@
* @hide
*/
@IntDef(prefix = {"VERIFICATION_STATE_"}, value = {
- UNVERIFIED,
- VERIFICATION_FAILED,
- VERIFIED
+ VERIFICATION_STATE_UNVERIFIED,
+ VERIFICATION_STATE_VERIFICATION_FAILED,
+ VERIFICATION_STATE_VERIFIED
})
@Retention(RetentionPolicy.SOURCE)
public @interface VerificationState {}
/**
- * Unverified state of a contact E2EE key.
+ * Unverified state of a contact end to end encrypted key.
*/
- public static final int UNVERIFIED = 0;
+ public static final int VERIFICATION_STATE_UNVERIFIED = 0;
/**
- * Failed verification state of a contact E2EE key.
+ * Failed verification state of a contact end to end encrypted key.
*/
- public static final int VERIFICATION_FAILED = 1;
+ public static final int VERIFICATION_STATE_VERIFICATION_FAILED = 1;
/**
- * Verified state of a contact E2EE key.
+ * Verified state of a contact end to end encrypted key.
*/
- public static final int VERIFIED = 2;
+ public static final int VERIFICATION_STATE_VERIFIED = 2;
/** @hide */
public static final class ContactKeys {
@@ -791,7 +792,7 @@
}
/**
- * A parcelable class encapsulating other users' E2EE contact key.
+ * A parcelable class encapsulating other users' end to end encrypted contact key.
*/
public static final class ContactKey implements Parcelable {
/**
@@ -1056,7 +1057,7 @@
}
/**
- * A parcelable class encapsulating self E2EE contact key.
+ * A parcelable class encapsulating self end to end encrypted contact key.
*/
public static final class SelfKey implements Parcelable {
/**
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 26f46cf..b026ce9 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -668,6 +668,23 @@
"android.settings.MANAGE_APP_LONG_RUNNING_JOBS";
/**
+ * Activity Action: Show settings to allow configuration of
+ * {@link Manifest.permission#RUN_BACKUP_JOBS} permission.
+ *
+ * Input: Optionally, the Intent's data URI can specify the application package name to
+ * directly invoke the management GUI specific to the package name. For example
+ * "package:com.my.app".
+ * <p>
+ * Output: When a package data uri is passed as input, the activity result is set to
+ * {@link android.app.Activity#RESULT_OK} if the permission was granted to the app. Otherwise,
+ * the result is set to {@link android.app.Activity#RESULT_CANCELED}.
+ */
+ @FlaggedApi(Flags.FLAG_BACKUP_TASKS_SETTINGS_SCREEN)
+ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+ public static final String ACTION_REQUEST_RUN_BACKUP_JOBS =
+ "android.settings.REQUEST_RUN_BACKUP_JOBS";
+
+ /**
* Activity Action: Show settings to allow configuration of cross-profile access for apps
*
* Input: Optionally, the Intent's data URI can specify the application package name to
@@ -11833,6 +11850,7 @@
* Whether to enable camera extensions software fallback.
* @hide
*/
+ @Readable
public static final String CAMERA_EXTENSIONS_FALLBACK = "camera_extensions_fallback";
/**
diff --git a/core/java/android/provider/flags.aconfig b/core/java/android/provider/flags.aconfig
index 0f12b13..ea1ac27 100644
--- a/core/java/android/provider/flags.aconfig
+++ b/core/java/android/provider/flags.aconfig
@@ -13,3 +13,10 @@
description: "This flag controls new E2EE contact keys API"
bug: "290696572"
}
+
+flag {
+ name: "backup_tasks_settings_screen"
+ namespace: "backstage_power"
+ description: "Add a new settings page for the RUN_BACKUP_JOBS permission."
+ bug: "320563660"
+}
diff --git a/core/java/android/service/appprediction/AppPredictionService.java b/core/java/android/service/appprediction/AppPredictionService.java
index a2ffa5d..2402cfd 100644
--- a/core/java/android/service/appprediction/AppPredictionService.java
+++ b/core/java/android/service/appprediction/AppPredictionService.java
@@ -18,6 +18,7 @@
import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
import android.annotation.CallSuper;
+import android.annotation.FlaggedApi;
import android.annotation.MainThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -31,12 +32,15 @@
import android.app.prediction.IPredictionCallback;
import android.content.Intent;
import android.content.pm.ParceledListSlice;
+import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.IBinder;
+import android.os.IRemoteCallback;
import android.os.Looper;
import android.os.RemoteException;
import android.service.appprediction.IPredictionService.Stub;
+import android.service.appprediction.flags.Flags;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Slog;
@@ -134,6 +138,16 @@
obtainMessage(AppPredictionService::doDestroyPredictionSession,
AppPredictionService.this, sessionId));
}
+
+ @FlaggedApi(Flags.FLAG_SERVICE_FEATURES_API)
+ @Override
+ public void requestServiceFeatures(AppPredictionSessionId sessionId,
+ IRemoteCallback callback) {
+ mHandler.sendMessage(
+ obtainMessage(AppPredictionService::onRequestServiceFeatures,
+ AppPredictionService.this, sessionId,
+ new RemoteCallbackWrapper(callback, null)));
+ }
};
@CallSuper
@@ -277,6 +291,18 @@
public void onDestroyPredictionSession(@NonNull AppPredictionSessionId sessionId) {}
/**
+ * Called by the client app to request {@link AppPredictionService} features info.
+ *
+ * @param sessionId the session's Id. It is @NonNull.
+ * @param callback the callback to return the Bundle which includes service features info. It
+ * is @NonNull.
+ */
+ @FlaggedApi(Flags.FLAG_SERVICE_FEATURES_API)
+ @MainThread
+ public void onRequestServiceFeatures(@NonNull AppPredictionSessionId sessionId,
+ @NonNull Consumer<Bundle> callback) {}
+
+ /**
* Used by the prediction factory to send back results the client app. The can be called
* in response to {@link #onRequestPredictionUpdate(AppPredictionSessionId)} or proactively as
* a result of changes in predictions.
@@ -357,4 +383,50 @@
}
}
}
+
+ private static final class RemoteCallbackWrapper implements Consumer<Bundle>,
+ IBinder.DeathRecipient {
+
+ private IRemoteCallback mCallback;
+ private final Consumer<RemoteCallbackWrapper> mOnBinderDied;
+
+ RemoteCallbackWrapper(IRemoteCallback callback,
+ @Nullable Consumer<RemoteCallbackWrapper> onBinderDied) {
+ mCallback = callback;
+ mOnBinderDied = onBinderDied;
+ if (mOnBinderDied != null) {
+ try {
+ mCallback.asBinder().linkToDeath(this, 0);
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Failed to link to death: " + e);
+ }
+ }
+ }
+
+ public void destroy() {
+ if (mCallback != null && mOnBinderDied != null) {
+ mCallback.asBinder().unlinkToDeath(this, 0);
+ }
+ }
+
+ @Override
+ public void accept(Bundle bundle) {
+ try {
+ if (mCallback != null) {
+ mCallback.sendResult(bundle);
+ }
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Error sending result:" + e);
+ }
+ }
+
+ @Override
+ public void binderDied() {
+ destroy();
+ mCallback = null;
+ if (mOnBinderDied != null) {
+ mOnBinderDied.accept(this);
+ }
+ }
+ }
}
diff --git a/core/java/android/service/appprediction/IPredictionService.aidl b/core/java/android/service/appprediction/IPredictionService.aidl
index 0f3df85..e144dfa 100644
--- a/core/java/android/service/appprediction/IPredictionService.aidl
+++ b/core/java/android/service/appprediction/IPredictionService.aidl
@@ -22,6 +22,7 @@
import android.app.prediction.AppPredictionSessionId;
import android.app.prediction.IPredictionCallback;
import android.content.pm.ParceledListSlice;
+import android.os.IRemoteCallback;
/**
* Interface from the system to a prediction service.
@@ -50,4 +51,6 @@
void requestPredictionUpdate(in AppPredictionSessionId sessionId);
void onDestroyPredictionSession(in AppPredictionSessionId sessionId);
+
+ void requestServiceFeatures(in AppPredictionSessionId sessionId, in IRemoteCallback callback);
}
diff --git a/core/java/android/service/appprediction/flags/flags.aconfig b/core/java/android/service/appprediction/flags/flags.aconfig
new file mode 100644
index 0000000..c7e47d4
--- /dev/null
+++ b/core/java/android/service/appprediction/flags/flags.aconfig
@@ -0,0 +1,8 @@
+package: "android.service.appprediction.flags"
+
+flag {
+ name: "service_features_api"
+ namespace: "systemui"
+ description: "Guards the new requestServiceFeatures api"
+ bug: "292565550"
+}
\ No newline at end of file
diff --git a/core/java/android/service/chooser/flags.aconfig b/core/java/android/service/chooser/flags.aconfig
index 3cc7f5a..add575b 100644
--- a/core/java/android/service/chooser/flags.aconfig
+++ b/core/java/android/service/chooser/flags.aconfig
@@ -8,6 +8,13 @@
}
flag {
+ name: "enable_sharesheet_metadata_extra"
+ namespace: "intentresolver"
+ description: "This flag enables sharesheet metadata to be displayed to users."
+ bug: "318942069"
+}
+
+flag {
name: "support_nfc_resolver"
namespace: "systemui"
description: "This flag controls the new NFC 'resolver' activity"
@@ -20,3 +27,10 @@
description: "This flag controls content toggling in Chooser"
bug: "302691505"
}
+
+flag {
+ name: "enable_chooser_result"
+ namespace: "intentresolver"
+ description: "Provides additional callbacks with information about user actions in ChooserResult"
+ bug: "263474465"
+}
diff --git a/core/java/android/text/BoringLayout.java b/core/java/android/text/BoringLayout.java
index a9a4581..2028c40 100644
--- a/core/java/android/text/BoringLayout.java
+++ b/core/java/android/text/BoringLayout.java
@@ -585,9 +585,7 @@
}
if (ClientFlags.fixLineHeightForLocale()) {
- if (minimumFontMetrics == null) {
- paint.getFontMetricsIntForLocale(fm);
- } else {
+ if (minimumFontMetrics != null) {
fm.set(minimumFontMetrics);
// Because the font metrics is provided by public APIs, adjust the top/bottom with
// ascent/descent: top must be smaller than ascent, bottom must be larger than
diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java
index 99bd2ff..5986238 100644
--- a/core/java/android/text/StaticLayout.java
+++ b/core/java/android/text/StaticLayout.java
@@ -767,22 +767,14 @@
}
int defaultTop;
- int defaultAscent;
- int defaultDescent;
+ final int defaultAscent;
+ final int defaultDescent;
int defaultBottom;
- if (ClientFlags.fixLineHeightForLocale()) {
- if (b.mMinimumFontMetrics != null) {
- defaultTop = (int) Math.floor(b.mMinimumFontMetrics.top);
- defaultAscent = Math.round(b.mMinimumFontMetrics.ascent);
- defaultDescent = Math.round(b.mMinimumFontMetrics.descent);
- defaultBottom = (int) Math.ceil(b.mMinimumFontMetrics.bottom);
- } else {
- paint.getFontMetricsIntForLocale(fm);
- defaultTop = fm.top;
- defaultAscent = fm.ascent;
- defaultDescent = fm.descent;
- defaultBottom = fm.bottom;
- }
+ if (ClientFlags.fixLineHeightForLocale() && b.mMinimumFontMetrics != null) {
+ defaultTop = (int) Math.floor(b.mMinimumFontMetrics.top);
+ defaultAscent = Math.round(b.mMinimumFontMetrics.ascent);
+ defaultDescent = Math.round(b.mMinimumFontMetrics.descent);
+ defaultBottom = (int) Math.ceil(b.mMinimumFontMetrics.bottom);
// Because the font metrics is provided by public APIs, adjust the top/bottom with
// ascent/descent: top must be smaller than ascent, bottom must be larger than descent.
@@ -1043,10 +1035,10 @@
if (endPos < spanEnd) {
// preserve metrics for current span
- fmTop = fm.top;
- fmBottom = fm.bottom;
- fmAscent = fm.ascent;
- fmDescent = fm.descent;
+ fmTop = Math.min(defaultTop, fm.top);
+ fmBottom = Math.max(defaultBottom, fm.bottom);
+ fmAscent = Math.min(defaultAscent, fm.ascent);
+ fmDescent = Math.max(defaultDescent, fm.descent);
} else {
fmTop = fmBottom = fmAscent = fmDescent = 0;
}
@@ -1069,7 +1061,7 @@
&& mLineCount < mMaximumVisibleLineCount) {
final MeasuredParagraph measuredPara =
MeasuredParagraph.buildForBidi(source, bufEnd, bufEnd, textDir, null);
- if (ClientFlags.fixLineHeightForLocale()) {
+ if (defaultAscent != 0 && defaultDescent != 0) {
fm.top = defaultTop;
fm.ascent = defaultAscent;
fm.descent = defaultDescent;
diff --git a/core/java/android/tracing/perfetto/TracingContext.java b/core/java/android/tracing/perfetto/TracingContext.java
index 0bce26e..c1a61a7 100644
--- a/core/java/android/tracing/perfetto/TracingContext.java
+++ b/core/java/android/tracing/perfetto/TracingContext.java
@@ -105,6 +105,5 @@
return res;
}
- // private static native void nativeFlush(long nativeDataSourcePointer);
private static native void nativeFlush(TracingContext thiz, long ctxPointer);
}
diff --git a/core/java/android/view/HandwritingInitiator.java b/core/java/android/view/HandwritingInitiator.java
index 0ce1d47..eb28920 100644
--- a/core/java/android/view/HandwritingInitiator.java
+++ b/core/java/android/view/HandwritingInitiator.java
@@ -23,8 +23,10 @@
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
+import android.view.inputmethod.Flags;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
+import android.widget.Editor;
import android.widget.TextView;
import com.android.internal.annotations.VisibleForTesting;
@@ -80,6 +82,16 @@
* connections and only set mConnectedView to null when mConnectionCount is zero.
*/
private int mConnectionCount = 0;
+
+ /**
+ * The reference to the View that currently has focus.
+ * This replaces mConnecteView when {@code Flags#intitiationWithoutInputConnection()} is
+ * enabled.
+ */
+ @Nullable
+ @VisibleForTesting
+ public WeakReference<View> mFocusedView = null;
+
private final InputMethodManager mImm;
private final int[] mTempLocation = new int[2];
@@ -112,9 +124,15 @@
*
* If the stylus is hovering on an unconnected editor that supports handwriting, we always show
* the hover icon.
+ * TODO(b/308827131): Rename to FocusedView after Flag is flipped.
*/
private boolean mShowHoverIconForConnectedView = true;
+ /** When flag is enabled, touched editors don't wait for InputConnection for initiation.
+ * However, delegation still waits for InputConnection.
+ */
+ private final boolean mInitiateWithoutConnection = Flags.initiationWithoutInputConnection();
+
@VisibleForTesting
public HandwritingInitiator(@NonNull ViewConfiguration viewConfiguration,
@NonNull InputMethodManager inputMethodManager) {
@@ -201,8 +219,8 @@
View candidateView = findBestCandidateView(mState.mStylusDownX,
mState.mStylusDownY, /* isHover */ false);
if (candidateView != null) {
- if (candidateView == getConnectedView()) {
- if (!candidateView.hasFocus()) {
+ if (candidateView == getConnectedOrFocusedView()) {
+ if (!mInitiateWithoutConnection && !candidateView.hasFocus()) {
requestFocusWithoutReveal(candidateView);
}
startHandwriting(candidateView);
@@ -217,8 +235,17 @@
candidateView.getHandwritingDelegatorCallback().run();
mState.mHasPreparedHandwritingDelegation = true;
} else {
- mState.mPendingConnectedView = new WeakReference<>(candidateView);
- requestFocusWithoutReveal(candidateView);
+ if (!mInitiateWithoutConnection) {
+ mState.mPendingConnectedView = new WeakReference<>(candidateView);
+ }
+ if (!candidateView.hasFocus()) {
+ requestFocusWithoutReveal(candidateView);
+ }
+ if (mInitiateWithoutConnection
+ && updateFocusedView(candidateView,
+ /* fromTouchEvent */ true)) {
+ startHandwriting(candidateView);
+ }
}
}
}
@@ -244,11 +271,7 @@
*/
public void onDelegateViewFocused(@NonNull View view) {
if (view == getConnectedView()) {
- if (tryAcceptStylusHandwritingDelegation(view)) {
- // A handwriting delegate view is accepted and handwriting starts; hide the
- // hover icon.
- mShowHoverIconForConnectedView = false;
- }
+ tryAcceptStylusHandwritingDelegation(view);
}
}
@@ -260,6 +283,10 @@
* @see #onInputConnectionClosed(View)
*/
public void onInputConnectionCreated(@NonNull View view) {
+ if (mInitiateWithoutConnection && !view.isHandwritingDelegate()) {
+ // When flag is enabled, only delegation continues to wait for InputConnection.
+ return;
+ }
if (!view.isAutoHandwritingEnabled()) {
clearConnectedView();
return;
@@ -274,12 +301,15 @@
// A new view just gain focus. By default, we should show hover icon for it.
mShowHoverIconForConnectedView = true;
if (view.isHandwritingDelegate() && tryAcceptStylusHandwritingDelegation(view)) {
- // A handwriting delegate view is accepted and handwriting starts; hide the
- // hover icon.
+ // tryAcceptStylusHandwritingDelegation should set boolean below, however, we
+ // cannot mock IMM to return true for acceptStylusDelegation().
+ // TODO(b/324670412): we should move any dependent tests to integration and remove
+ // the assignment below.
mShowHoverIconForConnectedView = false;
return;
}
- if (mState != null && mState.mPendingConnectedView != null
+ if (!mInitiateWithoutConnection && mState != null
+ && mState.mPendingConnectedView != null
&& mState.mPendingConnectedView.get() == view) {
startHandwriting(view);
}
@@ -293,6 +323,9 @@
* @param view the view that closed the InputConnection.
*/
public void onInputConnectionClosed(@NonNull View view) {
+ if (mInitiateWithoutConnection && !view.isHandwritingDelegate()) {
+ return;
+ }
final View connectedView = getConnectedView();
if (connectedView == null) return;
if (connectedView == view) {
@@ -306,6 +339,48 @@
}
}
+ @Nullable
+ private View getFocusedView() {
+ if (mFocusedView == null) return null;
+ return mFocusedView.get();
+ }
+
+ /**
+ * Clear the tracked focused view tracked for handwriting initiation.
+ * @param view the focused view.
+ */
+ public void clearFocusedView(View view) {
+ if (view == null || mFocusedView == null) {
+ return;
+ }
+ if (mFocusedView.get() == view) {
+ mFocusedView = null;
+ }
+ }
+
+ /**
+ * Called when new {@link Editor} is focused.
+ * @return {@code true} if handwriting can initiate for given view.
+ */
+ @VisibleForTesting
+ public boolean updateFocusedView(@NonNull View view, boolean fromTouchEvent) {
+ if (!view.shouldInitiateHandwriting()) {
+ mFocusedView = null;
+ return false;
+ }
+
+ final View focusedView = getFocusedView();
+ if (focusedView != view) {
+ mFocusedView = new WeakReference<>(view);
+ // A new view just gain focus. By default, we should show hover icon for it.
+ mShowHoverIconForConnectedView = true;
+ }
+ if (!fromTouchEvent) {
+ tryAcceptStylusHandwritingDelegation(view);
+ }
+ return true;
+ }
+
/** Starts a stylus handwriting session for the view. */
@VisibleForTesting
public void startHandwriting(@NonNull View view) {
@@ -324,6 +399,9 @@
*/
@VisibleForTesting
public boolean tryAcceptStylusHandwritingDelegation(@NonNull View view) {
+ if (!view.isHandwritingDelegate() || (mState != null && mState.mHasInitiatedHandwriting)) {
+ return false;
+ }
String delegatorPackageName =
view.getAllowedHandwritingDelegatorPackageName();
if (delegatorPackageName == null) {
@@ -337,6 +415,9 @@
if (view instanceof TextView) {
((TextView) view).hideHint();
}
+ // A handwriting delegate view is accepted and handwriting starts; hide the
+ // hover icon.
+ mShowHoverIconForConnectedView = false;
return true;
}
return false;
@@ -377,16 +458,25 @@
return PointerIcon.getSystemIcon(context, PointerIcon.TYPE_HANDWRITING);
}
- if (hoverView != getConnectedView()) {
+ if (hoverView != getConnectedOrFocusedView()) {
// The stylus is hovering on another view that supports handwriting. We should show
- // hover icon. Also reset the mShowHoverIconForConnectedView so that hover
- // icon is displayed again next time when the stylus hovers on connected view.
+ // hover icon. Also reset the mShowHoverIconForFocusedView so that hover
+ // icon is displayed again next time when the stylus hovers on focused view.
mShowHoverIconForConnectedView = true;
return PointerIcon.getSystemIcon(context, PointerIcon.TYPE_HANDWRITING);
}
return null;
}
+ // TODO(b/308827131): Remove once Flag is flipped.
+ private View getConnectedOrFocusedView() {
+ if (mInitiateWithoutConnection) {
+ return mFocusedView == null ? null : mFocusedView.get();
+ } else {
+ return mConnectedView == null ? null : mConnectedView.get();
+ }
+ }
+
private View getCachedHoverTarget() {
if (mCachedHoverTarget == null) {
return null;
@@ -458,20 +548,21 @@
*/
@Nullable
private View findBestCandidateView(float x, float y, boolean isHover) {
+ // TODO(b/308827131): Rename to FocusedView after Flag is flipped.
// If the connectedView is not null and do not set any handwriting area, it will check
// whether the connectedView's boundary contains the initial stylus position. If true,
// directly return the connectedView.
- final View connectedView = getConnectedView();
- if (connectedView != null) {
+ final View connectedOrFocusedView = getConnectedOrFocusedView();
+ if (connectedOrFocusedView != null) {
Rect handwritingArea = mTempRect;
- if (getViewHandwritingArea(connectedView, handwritingArea)
- && isInHandwritingArea(handwritingArea, x, y, connectedView, isHover)
- && shouldTriggerStylusHandwritingForView(connectedView)) {
+ if (getViewHandwritingArea(connectedOrFocusedView, handwritingArea)
+ && isInHandwritingArea(handwritingArea, x, y, connectedOrFocusedView, isHover)
+ && shouldTriggerStylusHandwritingForView(connectedOrFocusedView)) {
if (!isHover && mState != null) {
mState.mStylusDownWithinEditorBounds =
contains(handwritingArea, x, y, 0f, 0f, 0f, 0f);
}
- return connectedView;
+ return connectedOrFocusedView;
}
}
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index b5b81d1..29cc859 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -73,6 +73,7 @@
import android.window.ISurfaceSyncGroupCompletedListener;
import android.window.ITaskFpsCallback;
import android.window.ITrustedPresentationListener;
+import android.window.IUnhandledDragListener;
import android.window.InputTransferToken;
import android.window.ScreenCapture;
import android.window.TrustedPresentationThresholds;
@@ -1091,4 +1092,10 @@
@EnforcePermission("DETECT_SCREEN_RECORDING")
void unregisterScreenRecordingCallback(IScreenRecordingCallback callback);
+
+ /**
+ * Sets the listener to be called back when a cross-window drag and drop operation is unhandled
+ * (ie. not handled by any window which can handle the drag).
+ */
+ void setUnhandledDragListener(IUnhandledDragListener listener);
}
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index a9f1897..3dfd68a 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -30,6 +30,7 @@
import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_UNKNOWN;
import static android.view.displayhash.DisplayHashResultCallback.EXTRA_DISPLAY_HASH;
import static android.view.displayhash.DisplayHashResultCallback.EXTRA_DISPLAY_HASH_ERROR_CODE;
+import static android.view.flags.Flags.FLAG_SENSITIVE_CONTENT_APP_PROTECTION_API;
import static android.view.flags.Flags.FLAG_TOOLKIT_SET_FRAME_RATE_READ_ONLY;
import static android.view.flags.Flags.FLAG_VIEW_VELOCITY_API;
import static android.view.flags.Flags.enableUseMeasureCacheDuringForceLayout;
@@ -42,6 +43,7 @@
import static com.android.internal.util.FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS;
import static com.android.internal.util.FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__SINGLE_TAP;
import static com.android.internal.util.FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__UNKNOWN_CLASSIFICATION;
+import static com.android.window.flags.Flags.FLAG_DELEGATE_UNHANDLED_DRAGS;
import static java.lang.Math.max;
@@ -67,6 +69,7 @@
import android.annotation.TestApi;
import android.annotation.UiContext;
import android.annotation.UiThread;
+import android.app.PendingIntent;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.AutofillOptions;
import android.content.ClipData;
@@ -1946,6 +1949,41 @@
static final int TOOLTIP = 0x40000000;
/** @hide */
+ @IntDef(prefix = { "CONTENT_SENSITIVITY_" }, value = {
+ CONTENT_SENSITIVITY_AUTO,
+ CONTENT_SENSITIVITY_SENSITIVE,
+ CONTENT_SENSITIVITY_NOT_SENSITIVE
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface ContentSensitivity {}
+
+ /**
+ * Automatically determine whether a view displays sensitive content. For example, available
+ * autofill hints (or some other signal) can be used to determine if this view
+ * displays sensitive content.
+ *
+ * @see #getContentSensitivity()
+ */
+ @FlaggedApi(FLAG_SENSITIVE_CONTENT_APP_PROTECTION_API)
+ public static final int CONTENT_SENSITIVITY_AUTO = 0x0;
+
+ /**
+ * The view displays sensitive content.
+ *
+ * @see #getContentSensitivity()
+ */
+ @FlaggedApi(FLAG_SENSITIVE_CONTENT_APP_PROTECTION_API)
+ public static final int CONTENT_SENSITIVITY_SENSITIVE = 0x1;
+
+ /**
+ * The view doesn't display sensitive content.
+ *
+ * @see #getContentSensitivity()
+ */
+ @FlaggedApi(FLAG_SENSITIVE_CONTENT_APP_PROTECTION_API)
+ public static final int CONTENT_SENSITIVITY_NOT_SENSITIVE = 0x2;
+
+ /** @hide */
@IntDef(flag = true, prefix = { "FOCUSABLES_" }, value = {
FOCUSABLES_ALL,
FOCUSABLES_TOUCH_MODE
@@ -3646,6 +3684,7 @@
* 1 PFLAG4_ROTARY_HAPTICS_ENABLED
* 1 PFLAG4_ROTARY_HAPTICS_SCROLL_SINCE_LAST_ROTARY_INPUT
* 1 PFLAG4_ROTARY_HAPTICS_WAITING_FOR_SCROLL_EVENT
+ * 11 PFLAG4_CONTENT_SENSITIVITY_MASK
* |-------|-------|-------|-------|
*/
@@ -3762,6 +3801,15 @@
*/
private static final int PFLAG4_ROTARY_HAPTICS_WAITING_FOR_SCROLL_EVENT = 0x800000;
+ private static final int PFLAG4_CONTENT_SENSITIVITY_SHIFT = 24;
+
+ /**
+ * Mask for obtaining the bits which specify how to determine whether a view
+ * displays sensitive content or not.
+ */
+ private static final int PFLAG4_CONTENT_SENSITIVITY_MASK =
+ (CONTENT_SENSITIVITY_AUTO | CONTENT_SENSITIVITY_SENSITIVE
+ | CONTENT_SENSITIVITY_NOT_SENSITIVE) << PFLAG4_CONTENT_SENSITIVITY_SHIFT;
/* End of masks for mPrivateFlags4 */
/** @hide */
@@ -5283,6 +5331,34 @@
public static final int DRAG_FLAG_REQUEST_SURFACE_FOR_RETURN_ANIMATION = 1 << 11;
/**
+ * Flag indicating that a drag can cross window boundaries (within the same application). When
+ * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
+ * with this flag set, only visible windows belonging to the same application (ie. share the
+ * same UID) with targetSdkVersion >= {@link android.os.Build.VERSION_CODES#N API 24} will be
+ * able to participate in the drag operation and receive the dragged content.
+ *
+ * If both DRAG_FLAG_GLOBAL_SAME_APPLICATION and DRAG_FLAG_GLOBAL are set, then
+ * DRAG_FLAG_GLOBAL_SAME_APPLICATION takes precedence and the drag will only go to visible
+ * windows from the same application.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ public static final int DRAG_FLAG_GLOBAL_SAME_APPLICATION = 1 << 12;
+
+ /**
+ * Flag indicating that an unhandled drag should be delegated to the system to be started if no
+ * visible window wishes to handle the drop. When using this flag, the caller must provide
+ * ClipData with an Item that contains an immutable PendingIntent to an activity to be launched
+ * (not a broadcast, service, etc). See
+ * {@link ClipData.Item.Builder#setPendingIntent(PendingIntent)}.
+ *
+ * The system can decide to launch the intent or not based on factors like the current screen
+ * size or windowing mode. If the system does not launch the intent, it will be canceled via the
+ * normal drag and drop flow.
+ */
+ @FlaggedApi(FLAG_DELEGATE_UNHANDLED_DRAGS)
+ public static final int DRAG_FLAG_START_PENDING_INTENT_ON_UNHANDLED_DRAG = 1 << 13;
+
+ /**
* Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
*/
private float mVerticalScrollFactor;
@@ -10150,6 +10226,54 @@
}
/**
+ * Sets content sensitivity mode to determine whether this view displays sensitive content.
+ *
+ * @param mode {@link #CONTENT_SENSITIVITY_AUTO}, {@link #CONTENT_SENSITIVITY_NOT_SENSITIVE}
+ * or {@link #CONTENT_SENSITIVITY_SENSITIVE}
+ */
+ @FlaggedApi(FLAG_SENSITIVE_CONTENT_APP_PROTECTION_API)
+ public final void setContentSensitivity(@ContentSensitivity int mode) {
+ mPrivateFlags4 &= ~PFLAG4_CONTENT_SENSITIVITY_MASK;
+ mPrivateFlags4 |= ((mode << PFLAG4_CONTENT_SENSITIVITY_SHIFT)
+ & PFLAG4_CONTENT_SENSITIVITY_MASK);
+ }
+
+ /**
+ * Gets content sensitivity mode to determine whether this view displays sensitive content.
+ *
+ * <p>See {@link #setContentSensitivity(int)} and
+ * {@link #isContentSensitive()} for more info about this mode.
+ *
+ * @return {@link #CONTENT_SENSITIVITY_AUTO} by default, or value passed to
+ * {@link #setContentSensitivity(int)}.
+ */
+ @FlaggedApi(FLAG_SENSITIVE_CONTENT_APP_PROTECTION_API)
+ public @ContentSensitivity
+ final int getContentSensitivity() {
+ return (mPrivateFlags4 & PFLAG4_CONTENT_SENSITIVITY_MASK)
+ >> PFLAG4_CONTENT_SENSITIVITY_SHIFT;
+ }
+
+ /**
+ * Returns whether this view displays sensitive content, based
+ * on the value explicitly set by {@link #setContentSensitivity(int)}.
+ *
+ * @return whether the view displays sensitive content.
+ *
+ * @see #setContentSensitivity(int)
+ * @see #CONTENT_SENSITIVITY_AUTO
+ * @see #CONTENT_SENSITIVITY_SENSITIVE
+ * @see #CONTENT_SENSITIVITY_NOT_SENSITIVE
+ */
+ @FlaggedApi(FLAG_SENSITIVE_CONTENT_APP_PROTECTION_API)
+ public final boolean isContentSensitive() {
+ if (getContentSensitivity() == CONTENT_SENSITIVITY_SENSITIVE) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
* Gets the mode for determining whether this view is important for content capture.
*
* <p>See {@link #setImportantForContentCapture(int)} and
@@ -22175,6 +22299,9 @@
* Retrieve a unique token identifying the window this view is attached to.
* @return Return the window's token for use in
* {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
+ * This token maybe null if this view is not attached to a window.
+ * @see #isAttachedToWindow() for current window attach state
+ * @see OnAttachStateChangeListener to listen to window attach/detach state changes
*/
public IBinder getWindowToken() {
return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
@@ -28402,9 +28529,29 @@
Log.w(VIEW_LOG_TAG, "startDragAndDrop called with an invalid surface.");
return false;
}
+ if ((flags & DRAG_FLAG_GLOBAL) != 0 && ((flags & DRAG_FLAG_GLOBAL_SAME_APPLICATION) != 0)) {
+ Log.w(VIEW_LOG_TAG, "startDragAndDrop called with both DRAG_FLAG_GLOBAL "
+ + "and DRAG_FLAG_GLOBAL_SAME_APPLICATION, the drag will default to "
+ + "DRAG_FLAG_GLOBAL_SAME_APPLICATION");
+ flags &= ~DRAG_FLAG_GLOBAL;
+ }
if (data != null) {
- data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
+ if (com.android.window.flags.Flags.delegateUnhandledDrags()) {
+ data.prepareToLeaveProcess(
+ (flags & (DRAG_FLAG_GLOBAL_SAME_APPLICATION | DRAG_FLAG_GLOBAL)) != 0);
+ if ((flags & DRAG_FLAG_START_PENDING_INTENT_ON_UNHANDLED_DRAG) != 0) {
+ if (!data.hasActivityPendingIntents()) {
+ // Reset the flag if there is no launchable activity intent
+ flags &= ~DRAG_FLAG_START_PENDING_INTENT_ON_UNHANDLED_DRAG;
+ Log.w(VIEW_LOG_TAG, "startDragAndDrop called with "
+ + "DRAG_FLAG_START_INTENT_ON_UNHANDLED_DRAG but the clip data "
+ + "contains non-activity PendingIntents");
+ }
+ }
+ } else {
+ data.prepareToLeaveProcess((flags & DRAG_FLAG_GLOBAL) != 0);
+ }
}
Rect bounds = new Rect();
@@ -28430,6 +28577,7 @@
if (token != null) {
root.setLocalDragState(myLocalState);
mAttachInfo.mDragToken = token;
+ mAttachInfo.mDragData = data;
mAttachInfo.mViewRootImpl.setDragStartedViewForAccessibility(this);
setAccessibilityDragStarted(true);
}
@@ -28507,8 +28655,12 @@
if (mAttachInfo.mDragSurface != null) {
mAttachInfo.mDragSurface.release();
}
+ if (mAttachInfo.mDragData != null) {
+ mAttachInfo.mDragData.cleanUpPendingIntents();
+ }
mAttachInfo.mDragSurface = surface;
mAttachInfo.mDragToken = token;
+ mAttachInfo.mDragData = data;
// Cache the local state object for delivery with DragEvents
root.setLocalDragState(myLocalState);
if (a11yEnabled) {
@@ -31422,11 +31574,15 @@
IBinder mDragToken;
/**
+ * Used to track the data of the current drag operation for cleanup later.
+ */
+ ClipData mDragData;
+
+ /**
* The drag shadow surface for the current drag operation.
*/
public Surface mDragSurface;
-
/**
* The view that currently has a tooltip displayed.
*/
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 07c9795..28a7334 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -8599,6 +8599,10 @@
mAttachInfo.mDragSurface.release();
mAttachInfo.mDragSurface = null;
}
+ if (mAttachInfo.mDragData != null) {
+ mAttachInfo.mDragData.cleanUpPendingIntents();
+ mAttachInfo.mDragData = null;
+ }
}
}
}
diff --git a/core/java/android/view/WindowManagerImpl.java b/core/java/android/view/WindowManagerImpl.java
index ae00b70..2fb5213 100644
--- a/core/java/android/view/WindowManagerImpl.java
+++ b/core/java/android/view/WindowManagerImpl.java
@@ -520,11 +520,16 @@
public void registerTrustedPresentationListener(@NonNull IBinder window,
@NonNull TrustedPresentationThresholds thresholds, @NonNull Executor executor,
@NonNull Consumer<Boolean> listener) {
+ Objects.requireNonNull(window, "window must not be null");
+ Objects.requireNonNull(thresholds, "thresholds must not be null");
+ Objects.requireNonNull(executor, "executor must not be null");
+ Objects.requireNonNull(listener, "listener must not be null");
mGlobal.registerTrustedPresentationListener(window, thresholds, executor, listener);
}
@Override
public void unregisterTrustedPresentationListener(@NonNull Consumer<Boolean> listener) {
+ Objects.requireNonNull(listener, "listener must not be null");
mGlobal.unregisterTrustedPresentationListener(listener);
}
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 3d70c5b..3b07f27 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -18,6 +18,7 @@
import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
import static android.view.inputmethod.Flags.FLAG_HOME_SCREEN_HANDWRITING_DELEGATOR;
+import static android.view.inputmethod.Flags.initiationWithoutInputConnection;
import static android.view.inputmethod.InputConnection.CURSOR_UPDATE_IMMEDIATE;
import static android.view.inputmethod.InputConnection.CURSOR_UPDATE_MONITOR;
import static android.view.inputmethod.InputMethodEditorTraceProto.InputMethodClientsTraceProto.ClientSideProto.DISPLAY_ID;
@@ -1950,6 +1951,10 @@
if (mServedView != null) {
clearedView = mServedView;
mServedView = null;
+ if (initiationWithoutInputConnection() && clearedView.getViewRootImpl() != null) {
+ clearedView.getViewRootImpl().getHandwritingInitiator()
+ .clearFocusedView(clearedView);
+ }
}
if (clearedView != null) {
if (DEBUG) {
@@ -2932,6 +2937,10 @@
switch (res.result) {
case InputBindResult.ResultCode.ERROR_NOT_IME_TARGET_WINDOW:
mRestartOnNextWindowFocus = true;
+ if (initiationWithoutInputConnection()) {
+ mServedView.getViewRootImpl().getHandwritingInitiator().clearFocusedView(
+ mServedView);
+ }
mServedView = null;
break;
}
@@ -3094,6 +3103,11 @@
return false;
}
mServedView = mNextServedView;
+ if (initiationWithoutInputConnection() && mServedView.onCheckIsTextEditor()
+ && mServedView.isHandwritingDelegate()) {
+ mServedView.getViewRootImpl().getHandwritingInitiator().onDelegateViewFocused(
+ mServedView);
+ }
if (mServedInputConnection != null) {
mServedInputConnection.finishComposingTextFromImm();
}
diff --git a/core/java/android/view/inputmethod/flags.aconfig b/core/java/android/view/inputmethod/flags.aconfig
index 7f1cc8e..8b91bcb 100644
--- a/core/java/android/view/inputmethod/flags.aconfig
+++ b/core/java/android/view/inputmethod/flags.aconfig
@@ -62,3 +62,11 @@
bug: "311791923"
is_fixed_read_only: true
}
+
+flag {
+ name: "initiation_without_input_connection"
+ namespace: "input_method"
+ description: "Feature flag for initiating handwriting without InputConnection"
+ bug: "308827131"
+ is_fixed_read_only: true
+}
diff --git a/core/java/android/widget/EditText.java b/core/java/android/widget/EditText.java
index aa2474d7..3e0161a 100644
--- a/core/java/android/widget/EditText.java
+++ b/core/java/android/widget/EditText.java
@@ -16,9 +16,13 @@
package android.widget;
+import android.app.compat.CompatChanges;
+import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledSince;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
+import android.os.Build;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
@@ -29,6 +33,8 @@
import android.util.AttributeSet;
import android.view.KeyEvent;
+import com.android.internal.R;
+
/*
* This is supposed to be a *very* thin veneer over TextView.
* Do not make any changes here that do anything that a TextView
@@ -85,6 +91,11 @@
private static final int ID_ITALIC = android.R.id.italic;
private static final int ID_UNDERLINE = android.R.id.underline;
+ /** @hide */
+ @ChangeId
+ @EnabledSince(targetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM)
+ public static final long LINE_HEIGHT_FOR_LOCALE = 303326708L;
+
public EditText(Context context) {
this(context, null);
}
@@ -104,15 +115,39 @@
final TypedArray a = theme.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.EditText, defStyleAttr, defStyleRes);
- final int n = a.getIndexCount();
- for (int i = 0; i < n; ++i) {
- int attr = a.getIndex(i);
- switch (attr) {
- case com.android.internal.R.styleable.EditText_enableTextStylingShortcuts:
- mStyleShortcutsEnabled = a.getBoolean(attr, false);
- break;
+ try {
+ final int n = a.getIndexCount();
+ for (int i = 0; i < n; ++i) {
+ int attr = a.getIndex(i);
+ switch (attr) {
+ case com.android.internal.R.styleable.EditText_enableTextStylingShortcuts:
+ mStyleShortcutsEnabled = a.getBoolean(attr, false);
+ break;
+ }
}
+ } finally {
+ a.recycle();
}
+
+ boolean hasUseLocalePreferredLineHeightForMinimumInt = false;
+ boolean useLocalePreferredLineHeightForMinimumInt = false;
+ TypedArray tvArray = theme.obtainStyledAttributes(attrs,
+ com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes);
+ try {
+ hasUseLocalePreferredLineHeightForMinimumInt =
+ tvArray.hasValue(R.styleable.TextView_useLocalePreferredLineHeightForMinimum);
+ if (hasUseLocalePreferredLineHeightForMinimumInt) {
+ useLocalePreferredLineHeightForMinimumInt = tvArray.getBoolean(
+ R.styleable.TextView_useLocalePreferredLineHeightForMinimum, false);
+ }
+ } finally {
+ tvArray.recycle();
+ }
+ if (!hasUseLocalePreferredLineHeightForMinimumInt) {
+ useLocalePreferredLineHeightForMinimumInt =
+ CompatChanges.isChangeEnabled(LINE_HEIGHT_FOR_LOCALE);
+ }
+ setLocalePreferredLineHeightForMinimumUsed(useLocalePreferredLineHeightForMinimumInt);
}
@Override
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 9a4106d9..57e4e6a 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -867,6 +867,8 @@
private boolean mUseBoundsForWidth;
@Nullable private Paint.FontMetrics mMinimumFontMetrics;
+ @Nullable private Paint.FontMetrics mLocalePreferredFontMetrics;
+ private boolean mUseLocalePreferredLineHeightForMinimum;
@ViewDebug.ExportedProperty(category = "text")
@UnsupportedAppUsage
@@ -1617,6 +1619,11 @@
case com.android.internal.R.styleable.TextView_useBoundsForWidth:
mUseBoundsForWidth = a.getBoolean(attr, false);
hasUseBoundForWidthValue = true;
+ break;
+ case com.android.internal.R.styleable
+ .TextView_useLocalePreferredLineHeightForMinimum:
+ mUseLocalePreferredLineHeightForMinimum = a.getBoolean(attr, false);
+ break;
}
}
@@ -4992,6 +4999,41 @@
}
/**
+ * Returns true if the locale preferred line height is used for the minimum line height.
+ *
+ * @return true if using locale preferred line height for the minimum line height. Otherwise
+ * false.
+ *
+ * @see #setLocalePreferredLineHeightForMinimumUsed(boolean)
+ * @see #setMinimumFontMetrics(Paint.FontMetrics)
+ * @see #getMinimumFontMetrics()
+ */
+ @FlaggedApi(FLAG_FIX_LINE_HEIGHT_FOR_LOCALE)
+ public boolean isLocalePreferredLineHeightForMinimumUsed() {
+ return mUseLocalePreferredLineHeightForMinimum;
+ }
+
+ /**
+ * Set true if the locale preferred line height is used for the minimum line height.
+ *
+ * By setting this flag to true is equivalenet to call
+ * {@link #setMinimumFontMetrics(Paint.FontMetrics)} with the one obtained by
+ * {@link Paint#getFontMetricsForLocale(Paint.FontMetrics)}.
+ *
+ * If custom minimum line height was specified by
+ * {@link #setMinimumFontMetrics(Paint.FontMetrics)}, this flag will be ignored.
+ *
+ * @param flag true for using locale preferred line height for the minimum line height.
+ * @see #isLocalePreferredLineHeightForMinimumUsed()
+ * @see #setMinimumFontMetrics(Paint.FontMetrics)
+ * @see #getMinimumFontMetrics()
+ */
+ @FlaggedApi(FLAG_FIX_LINE_HEIGHT_FOR_LOCALE)
+ public void setLocalePreferredLineHeightForMinimumUsed(boolean flag) {
+ mUseLocalePreferredLineHeightForMinimum = flag;
+ }
+
+ /**
* @return whether fallback line spacing is enabled, {@code true} by default
*
* @see #setFallbackLineSpacing(boolean)
@@ -10728,6 +10770,21 @@
return alignment;
}
+ private Paint.FontMetrics getResolvedMinimumFontMetrics() {
+ if (mMinimumFontMetrics != null) {
+ return mMinimumFontMetrics;
+ }
+ if (!mUseLocalePreferredLineHeightForMinimum) {
+ return null;
+ }
+
+ if (mLocalePreferredFontMetrics == null) {
+ mLocalePreferredFontMetrics = new Paint.FontMetrics();
+ }
+ mTextPaint.getFontMetricsForLocale(mLocalePreferredFontMetrics);
+ return mLocalePreferredFontMetrics;
+ }
+
/**
* The width passed in is now the desired layout width,
* not the full view width with padding.
@@ -10792,7 +10849,8 @@
if (hintBoring == UNKNOWN_BORING) {
hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir,
isFallbackLineSpacingForBoringLayout(),
- mMinimumFontMetrics, mHintBoring);
+ getResolvedMinimumFontMetrics(), mHintBoring);
+
if (hintBoring != null) {
mHintBoring = hintBoring;
}
@@ -10842,7 +10900,8 @@
.setLineBreakConfig(LineBreakConfig.getLineBreakConfig(
mLineBreakStyle, mLineBreakWordStyle))
.setUseBoundsForWidth(mUseBoundsForWidth)
- .setMinimumFontMetrics(mMinimumFontMetrics);
+ .setMinimumFontMetrics(getResolvedMinimumFontMetrics());
+
if (shouldEllipsize) {
builder.setEllipsize(mEllipsize)
.setEllipsizedWidth(ellipsisWidth);
@@ -10907,12 +10966,13 @@
.setUseBoundsForWidth(mUseBoundsForWidth)
.setEllipsize(getKeyListener() == null ? effectiveEllipsize : null)
.setEllipsizedWidth(ellipsisWidth)
- .setMinimumFontMetrics(mMinimumFontMetrics);
+ .setMinimumFontMetrics(getResolvedMinimumFontMetrics());
result = builder.build();
} else {
if (boring == UNKNOWN_BORING) {
boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir,
- isFallbackLineSpacingForBoringLayout(), mMinimumFontMetrics, mBoring);
+ isFallbackLineSpacingForBoringLayout(), getResolvedMinimumFontMetrics(),
+ mBoring);
if (boring != null) {
mBoring = boring;
}
@@ -10926,7 +10986,7 @@
wantWidth, alignment, mSpacingMult, mSpacingAdd,
boring, mIncludePad, null, wantWidth,
isFallbackLineSpacingForBoringLayout(),
- mUseBoundsForWidth, mMinimumFontMetrics);
+ mUseBoundsForWidth, getResolvedMinimumFontMetrics());
} else {
result = new BoringLayout(
mTransformed,
@@ -10941,7 +11001,7 @@
null,
boring,
mUseBoundsForWidth,
- mMinimumFontMetrics);
+ getResolvedMinimumFontMetrics());
}
if (useSaved) {
@@ -10953,7 +11013,7 @@
wantWidth, alignment, mSpacingMult, mSpacingAdd,
boring, mIncludePad, effectiveEllipsize,
ellipsisWidth, isFallbackLineSpacingForBoringLayout(),
- mUseBoundsForWidth, mMinimumFontMetrics);
+ mUseBoundsForWidth, getResolvedMinimumFontMetrics());
} else {
result = new BoringLayout(
mTransformed,
@@ -10968,7 +11028,7 @@
effectiveEllipsize,
boring,
mUseBoundsForWidth,
- mMinimumFontMetrics);
+ getResolvedMinimumFontMetrics());
}
}
}
@@ -10988,7 +11048,7 @@
.setLineBreakConfig(LineBreakConfig.getLineBreakConfig(
mLineBreakStyle, mLineBreakWordStyle))
.setUseBoundsForWidth(mUseBoundsForWidth)
- .setMinimumFontMetrics(mMinimumFontMetrics);
+ .setMinimumFontMetrics(getResolvedMinimumFontMetrics());
if (shouldEllipsize) {
builder.setEllipsize(effectiveEllipsize)
.setEllipsizedWidth(ellipsisWidth);
@@ -11116,7 +11176,8 @@
if (des < 0) {
boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir,
- isFallbackLineSpacingForBoringLayout(), mMinimumFontMetrics, mBoring);
+ isFallbackLineSpacingForBoringLayout(), getResolvedMinimumFontMetrics(),
+ mBoring);
if (boring != null) {
mBoring = boring;
}
@@ -11156,7 +11217,7 @@
if (hintDes < 0) {
hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir,
- isFallbackLineSpacingForBoringLayout(), mMinimumFontMetrics,
+ isFallbackLineSpacingForBoringLayout(), getResolvedMinimumFontMetrics(),
mHintBoring);
if (hintBoring != null) {
mHintBoring = hintBoring;
@@ -11370,7 +11431,7 @@
.setLineBreakConfig(LineBreakConfig.getLineBreakConfig(
mLineBreakStyle, mLineBreakWordStyle))
.setUseBoundsForWidth(mUseBoundsForWidth)
- .setMinimumFontMetrics(mMinimumFontMetrics);
+ .setMinimumFontMetrics(getResolvedMinimumFontMetrics());
final StaticLayout layout = layoutBuilder.build();
diff --git a/core/java/android/widget/flags/notification_widget_flags.aconfig b/core/java/android/widget/flags/notification_widget_flags.aconfig
index 9f0b7c3..bfe3d05 100644
--- a/core/java/android/widget/flags/notification_widget_flags.aconfig
+++ b/core/java/android/widget/flags/notification_widget_flags.aconfig
@@ -5,4 +5,14 @@
namespace: "systemui"
description: "Enables notification specific LinearLayout optimization"
bug: "316110233"
+}
+
+flag {
+ name: "call_style_set_data_async"
+ namespace: "systemui"
+ description: "Offloads caller icon drawable loading to the background thread"
+ bug: "293961072"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
}
\ No newline at end of file
diff --git a/core/java/android/window/IUnhandledDragCallback.aidl b/core/java/android/window/IUnhandledDragCallback.aidl
new file mode 100644
index 0000000..7806b1f
--- /dev/null
+++ b/core/java/android/window/IUnhandledDragCallback.aidl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.window;
+
+import android.view.DragEvent;
+
+/**
+ * A callback for notifying the system when the unhandled drop is complete.
+ * {@hide}
+ */
+oneway interface IUnhandledDragCallback {
+ /**
+ * Called when the IUnhandledDropListener has fully handled the drop, and the drag can be
+ * cleaned up. If handled is `true`, then cleanup of the drag and drag surface will be
+ * immediate, otherwise, the system will treat the drag as a cancel back to the start of the
+ * drag.
+ */
+ void notifyUnhandledDropComplete(boolean handled);
+}
diff --git a/core/java/android/window/IUnhandledDragListener.aidl b/core/java/android/window/IUnhandledDragListener.aidl
new file mode 100644
index 0000000..52e9895
--- /dev/null
+++ b/core/java/android/window/IUnhandledDragListener.aidl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.window;
+
+import android.view.DragEvent;
+import android.window.IUnhandledDragCallback;
+
+/**
+ * An interface to a handler for global drags that are not consumed (ie. not handled by any window).
+ * {@hide}
+ */
+oneway interface IUnhandledDragListener {
+ /**
+ * Called when the user finishes the drag gesture but no windows have reported handling the
+ * drop. The DragEvent is populated with the drag surface for the listener to animate. The
+ * listener *MUST* call the provided callback exactly once when it has finished handling the
+ * drop. If the listener calls the callback with `true` then it is responsible for removing
+ * and releasing the drag surface passed through the DragEvent.
+ */
+ void onUnhandledDrop(in DragEvent event, in IUnhandledDragCallback callback);
+}
diff --git a/core/java/com/android/internal/os/TimeoutRecord.java b/core/java/com/android/internal/os/TimeoutRecord.java
index e9a8d4b..1f4abc1 100644
--- a/core/java/com/android/internal/os/TimeoutRecord.java
+++ b/core/java/com/android/internal/os/TimeoutRecord.java
@@ -45,6 +45,7 @@
TimeoutKind.APP_REGISTERED,
TimeoutKind.SHORT_FGS_TIMEOUT,
TimeoutKind.JOB_SERVICE,
+ TimeoutKind.FGS_TIMEOUT,
})
@Retention(RetentionPolicy.SOURCE)
@@ -59,6 +60,7 @@
int SHORT_FGS_TIMEOUT = 8;
int JOB_SERVICE = 9;
int APP_START = 10;
+ int FGS_TIMEOUT = 11;
}
/** Kind of timeout, e.g. BROADCAST_RECEIVER, etc. */
@@ -186,6 +188,12 @@
return TimeoutRecord.endingNow(TimeoutKind.SHORT_FGS_TIMEOUT, reason);
}
+ /** Record for a "foreground service" timeout. */
+ @NonNull
+ public static TimeoutRecord forFgsTimeout(String reason) {
+ return TimeoutRecord.endingNow(TimeoutKind.FGS_TIMEOUT, reason);
+ }
+
/** Record for a job related timeout. */
@NonNull
public static TimeoutRecord forJobService(String reason) {
diff --git a/core/java/com/android/internal/os/anr/AnrLatencyTracker.java b/core/java/com/android/internal/os/anr/AnrLatencyTracker.java
index f62ff38..e11067d 100644
--- a/core/java/com/android/internal/os/anr/AnrLatencyTracker.java
+++ b/core/java/com/android/internal/os/anr/AnrLatencyTracker.java
@@ -22,6 +22,7 @@
import static com.android.internal.util.FrameworkStatsLog.ANRLATENCY_REPORTED__ANR_TYPE__BROADCAST_OF_INTENT;
import static com.android.internal.util.FrameworkStatsLog.ANRLATENCY_REPORTED__ANR_TYPE__CONTENT_PROVIDER_NOT_RESPONDING;
import static com.android.internal.util.FrameworkStatsLog.ANRLATENCY_REPORTED__ANR_TYPE__EXECUTING_SERVICE;
+import static com.android.internal.util.FrameworkStatsLog.ANRLATENCY_REPORTED__ANR_TYPE__FGS_TIMEOUT;
import static com.android.internal.util.FrameworkStatsLog.ANRLATENCY_REPORTED__ANR_TYPE__INPUT_DISPATCHING_TIMEOUT;
import static com.android.internal.util.FrameworkStatsLog.ANRLATENCY_REPORTED__ANR_TYPE__INPUT_DISPATCHING_TIMEOUT_NO_FOCUSED_WINDOW;
import static com.android.internal.util.FrameworkStatsLog.ANRLATENCY_REPORTED__ANR_TYPE__JOB_SERVICE;
@@ -548,6 +549,8 @@
return ANRLATENCY_REPORTED__ANR_TYPE__SHORT_FGS_TIMEOUT;
case TimeoutKind.JOB_SERVICE:
return ANRLATENCY_REPORTED__ANR_TYPE__JOB_SERVICE;
+ case TimeoutKind.FGS_TIMEOUT:
+ return ANRLATENCY_REPORTED__ANR_TYPE__FGS_TIMEOUT;
default:
return ANRLATENCY_REPORTED__ANR_TYPE__UNKNOWN_ANR_TYPE;
}
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 3ee15ab..3d0ab4e 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -314,7 +314,8 @@
}
static void NativeSetApkAssets(JNIEnv* env, jclass /*clazz*/, jlong ptr,
- jobjectArray apk_assets_array, jboolean invalidate_caches) {
+ jobjectArray apk_assets_array, jboolean invalidate_caches,
+ jboolean preset) {
ATRACE_NAME("AssetManager::SetApkAssets");
const jsize apk_assets_len = env->GetArrayLength(apk_assets_array);
@@ -343,7 +344,11 @@
}
auto assetmanager = LockAndStartAssetManager(ptr);
- assetmanager->SetApkAssets(apk_assets, invalidate_caches);
+ if (preset) {
+ assetmanager->PresetApkAssets(apk_assets);
+ } else {
+ assetmanager->SetApkAssets(apk_assets, invalidate_caches);
+ }
}
static void NativeSetConfiguration(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint mcc, jint mnc,
@@ -353,7 +358,7 @@
jint screen_height, jint smallest_screen_width_dp,
jint screen_width_dp, jint screen_height_dp, jint screen_layout,
jint ui_mode, jint color_mode, jint grammatical_gender,
- jint major_version) {
+ jint major_version, jboolean force_refresh) {
ATRACE_NAME("AssetManager::SetConfiguration");
const jsize locale_count = (locales == NULL) ? 0 : env->GetArrayLength(locales);
@@ -413,7 +418,7 @@
}
auto assetmanager = LockAndStartAssetManager(ptr);
- assetmanager->SetConfigurations(configs);
+ assetmanager->SetConfigurations(std::move(configs), force_refresh != JNI_FALSE);
assetmanager->SetDefaultLocale(default_locale_int);
}
@@ -1522,8 +1527,8 @@
// AssetManager setup methods.
{"nativeCreate", "()J", (void*)NativeCreate},
{"nativeDestroy", "(J)V", (void*)NativeDestroy},
- {"nativeSetApkAssets", "(J[Landroid/content/res/ApkAssets;Z)V", (void*)NativeSetApkAssets},
- {"nativeSetConfiguration", "(JIILjava/lang/String;[Ljava/lang/String;IIIIIIIIIIIIIIII)V",
+ {"nativeSetApkAssets", "(J[Landroid/content/res/ApkAssets;ZZ)V", (void*)NativeSetApkAssets},
+ {"nativeSetConfiguration", "(JIILjava/lang/String;[Ljava/lang/String;IIIIIIIIIIIIIIIIZ)V",
(void*)NativeSetConfiguration},
{"nativeGetAssignedPackageIdentifiers", "(JZZ)Landroid/util/SparseArray;",
(void*)NativeGetAssignedPackageIdentifiers},
diff --git a/core/proto/android/hardware/sensorprivacy.proto b/core/proto/android/hardware/sensorprivacy.proto
index e368c6a..9359528 100644
--- a/core/proto/android/hardware/sensorprivacy.proto
+++ b/core/proto/android/hardware/sensorprivacy.proto
@@ -91,9 +91,6 @@
enum StateType {
ENABLED = 1;
DISABLED = 2;
- AUTO_DRIVER_ASSISTANCE_HELPFUL_APPS = 3;
- AUTO_DRIVER_ASSISTANCE_REQUIRED_APPS = 4;
- AUTO_DRIVER_ASSISTANCE_APPS = 5;
}
// DEPRECATED
@@ -137,4 +134,4 @@
// Source for which sensor privacy was toggled.
optional Source source = 1;
-}
+}
\ No newline at end of file
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 316001a..a2ce212 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1730,16 +1730,6 @@
android:description="@string/permdesc_cameraHeadlessSystemUser"
android:protectionLevel="signature" />
-
- <!-- @SystemApi Allows camera access of allowlisted driver assistance apps
- to be controlled separately.
- <p> Not for use by third-party applications.
- @FlaggedApi("com.android.internal.camera.flags.privacy_allowlist")
- @hide
- -->
- <permission android:name="android.permission.CAMERA_PRIVACY_ALLOWLIST"
- android:protectionLevel="signature|privileged" />
-
<!-- ====================================================================== -->
<!-- Permissions for accessing the device sensors -->
<!-- ====================================================================== -->
@@ -3839,6 +3829,7 @@
@hide This is not a third-party API (intended for OEMs and system apps). -->
<permission android:name="android.permission.MANAGE_ENHANCED_CONFIRMATION_STATES"
android:protectionLevel="signature|installer" />
+ <uses-permission android:name="android.permission.MANAGE_ENHANCED_CONFIRMATION_STATES" />
<!-- @SystemApi @hide Allows an application to set a device owner on retail demo devices.-->
<permission android:name="android.permission.PROVISION_DEMO_DEVICE"
@@ -7043,12 +7034,16 @@
<!-- Allows the holder to read blocked numbers. See
{@link android.provider.BlockedNumberContract}.
+ @SystemApi
+ @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies")
@hide -->
<permission android:name="android.permission.READ_BLOCKED_NUMBERS"
android:protectionLevel="signature" />
<!-- Allows the holder to write blocked numbers. See
{@link android.provider.BlockedNumberContract}.
+ @SystemApi
+ @FlaggedApi("com.android.server.telecom.flags.telecom_resolve_hidden_dependencies")
@hide -->
<permission android:name="android.permission.WRITE_BLOCKED_NUMBERS"
android:protectionLevel="signature" />
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 45861a3..41bc825 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -5857,6 +5857,23 @@
use glyph bound's as a source of text width. -->
<!-- @FlaggedApi("com.android.text.flags.use_bounds_for_width") -->
<attr name="useBoundsForWidth" format="boolean" />
+ <!-- Whether to use the locale preferred line height for the minimum line height.
+
+ This flag is useful for preventing jitter of entering letters into empty EditText.
+ The line height of the text is determined by the font files used for drawing text in a
+ line. However, in case of the empty text case, the line height cannot be determined and
+ the default line height: usually it is came from a font of Latin script. By making this
+ attribute to true, the TextView/EditText uses a line height that is likely used for the
+ locale associated with the widget. For example, if the system locale is Japanese, the
+ height of the EditText will be adjusted to meet the height of the Japanese font even if
+ the text is empty.
+
+ The default value for EditText is true if targetSdkVersion is
+ {@link android.os.Build.VERSION_CODE#VANILLA_ICE_CREAM} or later, otherwise false.
+ For other TextViews, the default value is false.
+ -->
+ <!-- @FlaggedApi("com.android.text.flags.fix_line_height_for_locale") -->
+ <attr name="useLocalePreferredLineHeightForMinimum" format="boolean" />
</declare-styleable>
<declare-styleable name="TextViewAppearance">
<!-- Base text color, typeface, size, and style. -->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index d4e727e..c6bc589 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2141,6 +2141,12 @@
<item>com.android.location.fused</item>
</string-array>
+ <!-- Package name of the extension software fallback. -->
+ <string name="config_extensionFallbackPackageName" translatable="false"></string>
+
+ <!-- Service name of the extension software fallback. -->
+ <string name="config_extensionFallbackServiceName" translatable="false"></string>
+
<!-- Package name(s) of Advanced Driver Assistance applications. These packages have additional
management of access to location, specific to driving assistance use-cases. They must be system
packages. This configuration is only applicable to devices that declare
diff --git a/core/res/res/values/config_telephony.xml b/core/res/res/values/config_telephony.xml
index c14fe57..78ce2d9 100644
--- a/core/res/res/values/config_telephony.xml
+++ b/core/res/res/values/config_telephony.xml
@@ -82,6 +82,13 @@
<bool name="config_wlan_data_service_conn_persistence_on_restart">true</bool>
<java-symbol type="bool" name="config_wlan_data_service_conn_persistence_on_restart" />
+ <!-- Indicating whether the retry timer from setup data call response for data throttling should
+ be honored for emergency network request. By default this is off, meaning for emergency
+ network requests, the data frameworks will ignore the previous retry timer passed in from
+ setup data call response. -->
+ <bool name="config_honor_data_retry_timer_for_emergency_network">false</bool>
+ <java-symbol type="bool" name="config_honor_data_retry_timer_for_emergency_network" />
+
<!-- Cellular data service package name to bind to by default. If none is specified in an
overlay, an empty string is passed in -->
<string name="config_wwan_data_service_package" translatable="false">com.android.phone</string>
@@ -212,6 +219,11 @@
<integer name="config_emergency_call_wait_for_connection_timeout_millis">20000</integer>
<java-symbol type="integer" name="config_emergency_call_wait_for_connection_timeout_millis" />
+ <!-- Indicates the data limit in bytes that can be used for bootstrap sim until factory reset.
+ -1 means unlimited. -->
+ <integer name="config_esim_bootstrap_data_limit_bytes">-1</integer>
+ <java-symbol type="integer" name="config_esim_bootstrap_data_limit_bytes" />
+
<!-- Telephony config for the PLMNs of all satellite providers. This is used by satellite modem
to identify providers that should be ignored if the carrier config
carrier_supported_satellite_services_per_provider_bundle does not support them.
diff --git a/core/res/res/values/public-staging.xml b/core/res/res/values/public-staging.xml
index 0a6779a9..5ee5555 100644
--- a/core/res/res/values/public-staging.xml
+++ b/core/res/res/values/public-staging.xml
@@ -153,6 +153,8 @@
<public name="requireContentUriPermissionFromCaller" />
<!-- @FlaggedApi("android.view.inputmethod.ime_switcher_revamp") -->
<public name="languageSettingsActivity"/>
+ <!-- @FlaggedApi("com.android.text.flags.fix_line_height_for_locale") -->
+ <public name="useLocalePreferredLineHeightForMinimum"/>
</staging-public-group>
<staging-public-group type="id" first-id="0x01bc0000">
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 3df7570..3d19c85 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2154,6 +2154,8 @@
<java-symbol type="string" name="config_systemImageEditor" />
<java-symbol type="string" name="config_datause_iface" />
<java-symbol type="string" name="config_activityRecognitionHardwarePackageName" />
+ <java-symbol type="string" name="config_extensionFallbackPackageName" />
+ <java-symbol type="string" name="config_extensionFallbackServiceName" />
<java-symbol type="string" name="config_fusedLocationProviderPackageName" />
<java-symbol type="string" name="config_gnssLocationProviderPackageName" />
<java-symbol type="string" name="config_geocoderProviderPackageName" />
diff --git a/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java b/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java
index 610b8ae..0b0fd66 100644
--- a/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java
+++ b/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java
@@ -19,10 +19,12 @@
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.IAccessibilityServiceConnection;
+import android.accessibilityservice.IBrailleDisplayController;
import android.accessibilityservice.MagnificationConfig;
import android.annotation.NonNull;
import android.content.pm.ParceledListSlice;
import android.graphics.Region;
+import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteCallback;
@@ -237,4 +239,15 @@
int accessibilityWindowId,
SurfaceControl sc,
IAccessibilityInteractionConnectionCallback callback) {}
+
+ @Override
+ public void connectBluetoothBrailleDisplay(String bluetoothAddress,
+ IBrailleDisplayController controller) {}
+
+ @Override
+ public void connectUsbBrailleDisplay(UsbDevice usbDevice,
+ IBrailleDisplayController controller) {}
+
+ @Override
+ public void setTestBrailleDisplayData(List<Bundle> brailleDisplays) {}
}
diff --git a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
index f39bddd..51eb41c 100644
--- a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
+++ b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java
@@ -20,10 +20,12 @@
import static android.view.MotionEvent.ACTION_HOVER_MOVE;
import static android.view.MotionEvent.ACTION_MOVE;
import static android.view.MotionEvent.ACTION_UP;
+import static android.view.inputmethod.Flags.initiationWithoutInputConnection;
import static android.view.stylus.HandwritingTestUtil.createView;
import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assume.assumeFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyFloat;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -91,6 +93,7 @@
private EditText mTestView1;
private EditText mTestView2;
private Context mContext;
+ private boolean mInitiateWithoutConnection;
@Before
public void setup() throws Exception {
@@ -119,6 +122,7 @@
mHandwritingInitiator.updateHandwritingAreasForView(mTestView1);
mHandwritingInitiator.updateHandwritingAreasForView(mTestView2);
doReturn(true).when(mHandwritingInitiator).tryAcceptStylusHandwritingDelegation(any());
+ mInitiateWithoutConnection = initiationWithoutInputConnection();
}
@Test
@@ -194,7 +198,9 @@
mTestView1.setText("hello");
when(mTestView1.getOffsetForPosition(anyFloat(), anyFloat())).thenReturn(4);
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ if (!mInitiateWithoutConnection) {
+ mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ }
final int x1 = sHwArea1.left - HW_BOUNDS_OFFSETS_LEFT_PX / 2;
final int y1 = sHwArea1.top - HW_BOUNDS_OFFSETS_TOP_PX / 2;
MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
@@ -214,7 +220,7 @@
}
@Test
- public void onTouchEvent_startHandwriting_inputConnectionBuiltAfterStylusMove() {
+ public void onTouchEvent_startHandwriting_servedViewUpdateAfterStylusMove() {
final int x1 = (sHwArea1.left + sHwArea1.right) / 2;
final int y1 = (sHwArea1.top + sHwArea1.bottom) / 2;
MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
@@ -225,14 +231,19 @@
MotionEvent stylusEvent2 = createStylusEvent(ACTION_MOVE, x2, y2, 0);
mHandwritingInitiator.onTouchEvent(stylusEvent2);
- // InputConnection is created after stylus movement.
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ if (mInitiateWithoutConnection) {
+ // Focus is changed after stylus movement.
+ mHandwritingInitiator.updateFocusedView(mTestView1, /*fromTouchEvent*/ true);
+ } else {
+ // InputConnection is created after stylus movement.
+ mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ }
verify(mHandwritingInitiator, times(1)).startHandwriting(mTestView1);
}
@Test
- public void onTouchEvent_startHandwriting_inputConnectionBuilt_stylusMoveInExtendedHWArea() {
+ public void onTouchEvent_startHandwriting_servedViewUpdate_stylusMoveInExtendedHWArea() {
mTestView1.setText("hello");
when(mTestView1.getOffsetForPosition(anyFloat(), anyFloat())).thenReturn(4);
// The stylus down point is between mTestView1 and mTestView2, but it is within the
@@ -247,21 +258,35 @@
MotionEvent stylusEvent2 = createStylusEvent(ACTION_MOVE, x2, y2, 0);
mHandwritingInitiator.onTouchEvent(stylusEvent2);
- // First create InputConnection for mTestView2 and verify that handwriting is not started.
- mHandwritingInitiator.onInputConnectionCreated(mTestView2);
- verify(mHandwritingInitiator, never()).startHandwriting(mTestView2);
+ if (!mInitiateWithoutConnection) {
+ // First create InputConnection for mTestView2 and verify that handwriting is not
+ // started.
+ mHandwritingInitiator.onInputConnectionCreated(mTestView2);
+ }
- // Next create InputConnection for mTextView1. Handwriting is started for this view since
- // the stylus down point is closest to this view.
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ // Note: mTestView2 receives focus when initiationWithoutInputConnection() is enabled.
+ // verify that handwriting is not started.
+ verify(mHandwritingInitiator, never()).startHandwriting(mTestView2);
+ if (mInitiateWithoutConnection) {
+ // Focus is changed after stylus movement.
+ mHandwritingInitiator.updateFocusedView(mTestView1, /*fromTouchEvent*/ true);
+ } else {
+ // Next create InputConnection for mTextView1. Handwriting is started for this view
+ // since the stylus down point is closest to this view.
+ mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ }
+ // Handwriting is started for this view since the stylus down point is closest to this
+ // view.
verify(mHandwritingInitiator).startHandwriting(mTestView1);
// Since the stylus down point was outside the TextView's bounds, the handwriting initiator
// sets the cursor position.
verify(mTestView1).setSelection(4);
}
+
@Test
public void onTouchEvent_tryAcceptDelegation_delegatorCallbackCreatesInputConnection() {
+ assumeFalse(mInitiateWithoutConnection);
View delegateView = new EditText(mContext);
delegateView.setIsHandwritingDelegate(true);
@@ -281,6 +306,7 @@
verify(mHandwritingInitiator, times(1)).tryAcceptStylusHandwritingDelegation(delegateView);
}
+
@Test
public void onTouchEvent_tryAcceptDelegation_delegatorCallbackFocusesDelegate() {
View delegateView = new EditText(mContext);
@@ -288,8 +314,14 @@
mHandwritingInitiator.onInputConnectionCreated(delegateView);
reset(mHandwritingInitiator);
- mTestView1.setHandwritingDelegatorCallback(
- () -> mHandwritingInitiator.onDelegateViewFocused(delegateView));
+ if (mInitiateWithoutConnection) {
+ mTestView1.setHandwritingDelegatorCallback(
+ () -> mHandwritingInitiator.updateFocusedView(
+ delegateView, /*fromTouchEvent*/ false));
+ } else {
+ mTestView1.setHandwritingDelegatorCallback(
+ () -> mHandwritingInitiator.onDelegateViewFocused(delegateView));
+ }
final int x1 = (sHwArea1.left + sHwArea1.right) / 2;
final int y1 = (sHwArea1.top + sHwArea1.bottom) / 2;
@@ -339,6 +371,14 @@
assertThat(onTouchEventResult4).isTrue();
}
+ private void callOnInputConnectionOrUpdateViewFocus(View view) {
+ if (mInitiateWithoutConnection) {
+ mHandwritingInitiator.updateFocusedView(view, /*fromTouchEvent*/ true);
+ } else {
+ mHandwritingInitiator.onInputConnectionCreated(view);
+ }
+ }
+
@Test
public void onTouchEvent_notStartHandwriting_whenHandwritingNotAvailable() {
final Rect rect = new Rect(600, 600, 900, 900);
@@ -346,7 +386,7 @@
false /* isStylusHandwritingAvailable */);
mHandwritingInitiator.updateHandwritingAreasForView(testView);
- mHandwritingInitiator.onInputConnectionCreated(testView);
+ callOnInputConnectionOrUpdateViewFocus(testView);
final int x1 = (rect.left + rect.right) / 2;
final int y1 = (rect.top + rect.bottom) / 2;
MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
@@ -365,7 +405,7 @@
@Test
public void onTouchEvent_notStartHandwriting_when_stylusTap_withinHWArea() {
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ callOnInputConnectionOrUpdateViewFocus(mTestView1);
final int x1 = 200;
final int y1 = 200;
MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
@@ -381,7 +421,7 @@
@Test
public void onTouchEvent_notStartHandwriting_when_stylusMove_outOfHWArea() {
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ callOnInputConnectionOrUpdateViewFocus(mTestView1);
final int x1 = 10;
final int y1 = 10;
MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
@@ -397,7 +437,7 @@
@Test
public void onTouchEvent_notStartHandwriting_when_stylusMove_afterTimeOut() {
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ callOnInputConnectionOrUpdateViewFocus(mTestView1);
final int x1 = 10;
final int y1 = 10;
final long time1 = 10L;
@@ -433,8 +473,9 @@
@Test
public void onTouchEvent_focusView_inputConnectionAlreadyBuilt_stylusMoveOnce_withinHWArea() {
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
-
+ if (!mInitiateWithoutConnection) {
+ mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ }
final int x1 = (sHwArea1.left + sHwArea1.right) / 2;
final int y1 = (sHwArea1.top + sHwArea1.bottom) / 2;
MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
@@ -487,14 +528,14 @@
verify(mTestView2, times(1)).requestFocus();
- mHandwritingInitiator.onInputConnectionCreated(mTestView2);
+ callOnInputConnectionOrUpdateViewFocus(mTestView2);
verify(mHandwritingInitiator, times(1)).startHandwriting(mTestView2);
}
@Test
public void onTouchEvent_handwritingAreaOverlapped_focusedViewHasPriority() {
// Simulate the case where mTestView1 is focused.
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ callOnInputConnectionOrUpdateViewFocus(mTestView1);
// The ACTION_DOWN location is within the handwriting bounds of both mTestView1 and
// mTestView2. Although it's closer to mTestView2's handwriting bounds, handwriting is
// initiated for mTestView1 because it's focused.
@@ -559,9 +600,14 @@
// Set mTextView2 to be the delegate of mTestView1.
mTestView2.setIsHandwritingDelegate(true);
- mTestView1.setHandwritingDelegatorCallback(
- () -> mHandwritingInitiator.onInputConnectionCreated(mTestView2));
-
+ if (mInitiateWithoutConnection) {
+ mTestView1.setHandwritingDelegatorCallback(
+ () -> mHandwritingInitiator.updateFocusedView(
+ mTestView2, /*fromTouchEvent*/ false));
+ } else {
+ mTestView1.setHandwritingDelegatorCallback(
+ () -> mHandwritingInitiator.onInputConnectionCreated(mTestView2));
+ }
injectStylusEvent(mHandwritingInitiator, sHwArea1.centerX(), sHwArea1.centerY(),
/* exceedsHWSlop */ true);
// Prerequisite check, verify that handwriting started for delegateView.
@@ -610,8 +656,13 @@
assertThat(icon1).isNull();
// Simulate that focus is switched to mTestView2 first and then switched back.
- mHandwritingInitiator.onInputConnectionCreated(mTestView2);
- mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ if (mInitiateWithoutConnection) {
+ mHandwritingInitiator.updateFocusedView(mTestView2, /*fromTouchEvent*/ true);
+ mHandwritingInitiator.updateFocusedView(mTestView1, /*fromTouchEvent*/ true);
+ } else {
+ mHandwritingInitiator.onInputConnectionCreated(mTestView2);
+ mHandwritingInitiator.onInputConnectionCreated(mTestView1);
+ }
PointerIcon icon2 = mHandwritingInitiator.onResolvePointerIcon(mContext, hoverEvent1);
// After the change of focus, hover icon shows again.
@@ -620,9 +671,15 @@
@Test
public void autoHandwriting_whenDisabled_wontStartHW() {
- View mockView = createView(sHwArea1, false /* autoHandwritingEnabled */,
- true /* isStylusHandwritingAvailable */);
- mHandwritingInitiator.onInputConnectionCreated(mockView);
+ if (mInitiateWithoutConnection) {
+ mTestView1.setAutoHandwritingEnabled(false);
+ mTestView1.setHandwritingDelegatorCallback(null);
+ mHandwritingInitiator.updateFocusedView(mTestView1, /*fromTouchEvent*/ true);
+ } else {
+ View mockView = createView(sHwArea1, false /* autoHandwritingEnabled */,
+ true /* isStylusHandwritingAvailable */);
+ mHandwritingInitiator.onInputConnectionCreated(mockView);
+ }
final int x1 = (sHwArea1.left + sHwArea1.right) / 2;
final int y1 = (sHwArea1.top + sHwArea1.bottom) / 2;
MotionEvent stylusEvent1 = createStylusEvent(ACTION_DOWN, x1, y1, 0);
@@ -639,6 +696,7 @@
@Test
public void onInputConnectionCreated() {
+ assumeFalse(mInitiateWithoutConnection);
mHandwritingInitiator.onInputConnectionCreated(mTestView1);
assertThat(mHandwritingInitiator.mConnectedView).isNotNull();
assertThat(mHandwritingInitiator.mConnectedView.get()).isEqualTo(mTestView1);
@@ -646,6 +704,7 @@
@Test
public void onInputConnectionCreated_whenAutoHandwritingIsDisabled() {
+ assumeFalse(mInitiateWithoutConnection);
View view = new View(mContext);
view.setAutoHandwritingEnabled(false);
assertThat(view.isAutoHandwritingEnabled()).isFalse();
@@ -656,6 +715,7 @@
@Test
public void onInputConnectionClosed() {
+ assumeFalse(mInitiateWithoutConnection);
mHandwritingInitiator.onInputConnectionCreated(mTestView1);
mHandwritingInitiator.onInputConnectionClosed(mTestView1);
@@ -664,6 +724,7 @@
@Test
public void onInputConnectionClosed_whenAutoHandwritingIsDisabled() {
+ assumeFalse(mInitiateWithoutConnection);
View view = new View(mContext);
view.setAutoHandwritingEnabled(false);
mHandwritingInitiator.onInputConnectionCreated(view);
@@ -674,6 +735,7 @@
@Test
public void onInputConnectionCreated_inputConnectionRestarted() {
+ assumeFalse(mInitiateWithoutConnection);
// When IMM restarts input connection, View#onInputConnectionCreatedInternal might be
// called before View#onInputConnectionClosedInternal. As a result, we need to handle the
// case where "one view "2 InputConnections".
diff --git a/core/tests/devicestatetests/Android.bp b/core/tests/devicestatetests/Android.bp
index 7748de5..60848b3 100644
--- a/core/tests/devicestatetests/Android.bp
+++ b/core/tests/devicestatetests/Android.bp
@@ -29,6 +29,8 @@
"androidx.test.rules",
"frameworks-base-testutils",
"mockito-target-minus-junit4",
+ "platform-test-annotations",
+ "testng",
],
libs: ["android.test.runner"],
platform_apis: true,
diff --git a/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateTest.java b/core/tests/devicestatetests/src/android/hardware/devicestate/DeviceStateTest.java
similarity index 93%
rename from services/tests/servicestests/src/com/android/server/devicestate/DeviceStateTest.java
rename to core/tests/devicestatetests/src/android/hardware/devicestate/DeviceStateTest.java
index d54524e..396d403 100644
--- a/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateTest.java
+++ b/core/tests/devicestatetests/src/android/hardware/devicestate/DeviceStateTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.devicestate;
+package android.hardware.devicestate;
import static android.hardware.devicestate.DeviceStateManager.MAXIMUM_DEVICE_STATE;
import static android.hardware.devicestate.DeviceStateManager.MINIMUM_DEVICE_STATE;
@@ -25,18 +25,17 @@
import android.platform.test.annotations.Presubmit;
-import androidx.test.runner.AndroidJUnit4;
-
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
- * Unit tests for {@link DeviceState}.
+ * Unit tests for {@link android.hardware.devicestate.DeviceState}.
* <p/>
* Run with <code>atest DeviceStateTest</code>.
*/
@Presubmit
-@RunWith(AndroidJUnit4.class)
+@RunWith(JUnit4.class)
public final class DeviceStateTest {
@Test
public void testConstruct() {
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 0baaff0..fdb5208 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -575,6 +575,11 @@
<permission name="android.permission.READ_SYSTEM_GRAMMATICAL_GENDER"/>
<!-- Permissions required for CTS test - CtsContactKeysProviderPrivilegedApp -->
<permission name="android.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS"/>
+ <!-- Permission required for CTS test BlockedNumberContractTest -->
+ <permission name="android.permission.WRITE_BLOCKED_NUMBERS" />
+ <permission name="android.permission.READ_BLOCKED_NUMBERS" />
+ <!-- Permission required for CTS test - PackageManagerTest -->
+ <permission name="android.permission.DOMAIN_VERIFICATION_AGENT"/>
</privapp-permissions>
<privapp-permissions package="com.android.statementservice">
diff --git a/libs/WindowManager/Shell/multivalentTests/src/com/android/wm/shell/bubbles/BubblePositionerTest.kt b/libs/WindowManager/Shell/multivalentTests/src/com/android/wm/shell/bubbles/BubblePositionerTest.kt
index ea7c6ed..5825bbf 100644
--- a/libs/WindowManager/Shell/multivalentTests/src/com/android/wm/shell/bubbles/BubblePositionerTest.kt
+++ b/libs/WindowManager/Shell/multivalentTests/src/com/android/wm/shell/bubbles/BubblePositionerTest.kt
@@ -165,6 +165,25 @@
}
@Test
+ fun testGetRestingPosition_afterBoundsChange() {
+ positioner.update(defaultDeviceConfig.copy(isLargeScreen = true,
+ windowBounds = Rect(0, 0, 2000, 1600)))
+
+ // Set the resting position to the right side
+ var allowableStackRegion = positioner.getAllowableStackPositionRegion(1 /* bubbleCount */)
+ val restingPosition = PointF(allowableStackRegion.right, allowableStackRegion.centerY())
+ positioner.restingPosition = restingPosition
+
+ // Now make the device smaller
+ positioner.update(defaultDeviceConfig.copy(isLargeScreen = false,
+ windowBounds = Rect(0, 0, 1000, 1600)))
+
+ // Check the resting position is on the correct side
+ allowableStackRegion = positioner.getAllowableStackPositionRegion(1 /* bubbleCount */)
+ assertThat(positioner.restingPosition.x).isEqualTo(allowableStackRegion.right)
+ }
+
+ @Test
fun testHasUserModifiedDefaultPosition_false() {
positioner.update(defaultDeviceConfig.copy(isLargeScreen = true, isRtl = true))
assertThat(positioner.hasUserModifiedDefaultPosition()).isFalse()
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
index c03b6f8..cda29c9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
@@ -120,6 +120,13 @@
@VisibleForTesting
public void updateInternal(int rotation, Insets insets, Rect bounds) {
+ BubbleStackView.RelativeStackPosition prevStackPosition = null;
+ if (mRestingStackPosition != null && mScreenRect != null && !mScreenRect.equals(bounds)) {
+ // Save the resting position as a relative position with the previous bounds, at the
+ // end of the update we'll restore it based on the new bounds.
+ prevStackPosition = new BubbleStackView.RelativeStackPosition(getRestingPosition(),
+ getAllowableStackPositionRegion(1));
+ }
mRotation = rotation;
mInsets = insets;
@@ -182,6 +189,12 @@
R.dimen.bubbles_flyout_min_width_large_screen);
mMaxBubbles = calculateMaxBubbles();
+
+ if (prevStackPosition != null) {
+ // Get the new resting position based on the updated values
+ mRestingStackPosition = prevStackPosition.getAbsolutePositionInRegion(
+ getAllowableStackPositionRegion(1));
+ }
}
/**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
index ead5ad2..bd9d89c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
@@ -64,6 +64,7 @@
import com.android.wm.shell.desktopmode.ExitDesktopTaskTransitionHandler;
import com.android.wm.shell.desktopmode.ToggleResizeDesktopTaskTransitionHandler;
import com.android.wm.shell.draganddrop.DragAndDropController;
+import com.android.wm.shell.draganddrop.UnhandledDragController;
import com.android.wm.shell.freeform.FreeformComponents;
import com.android.wm.shell.freeform.FreeformTaskListener;
import com.android.wm.shell.freeform.FreeformTaskTransitionHandler;
@@ -558,6 +559,14 @@
@WMSingleton
@Provides
+ static UnhandledDragController provideUnhandledDragController(
+ IWindowManager wmService,
+ @ShellMainThread ShellExecutor mainExecutor) {
+ return new UnhandledDragController(wmService, mainExecutor);
+ }
+
+ @WMSingleton
+ @Provides
static DragAndDropController provideDragAndDropController(Context context,
ShellInit shellInit,
ShellController shellController,
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java
index 605600f..ba08b09 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/EnterDesktopTaskTransitionHandler.java
@@ -143,7 +143,7 @@
final SurfaceControl leash = change.getLeash();
final Rect startBounds = change.getStartAbsBounds();
- startT.setPosition(leash, startBounds.left, startBounds.right)
+ startT.setPosition(leash, startBounds.left, startBounds.top)
.setWindowCrop(leash, startBounds.width(), startBounds.height())
.show(leash);
mDesktopModeWindowDecoration.showResizeVeil(startT, startBounds);
@@ -154,7 +154,7 @@
SurfaceControl.Transaction t = mTransactionSupplier.get();
animator.addUpdateListener(animation -> {
final Rect animationValue = (Rect) animator.getAnimatedValue();
- t.setPosition(leash, animationValue.left, animationValue.right)
+ t.setPosition(leash, animationValue.left, animationValue.top)
.setWindowCrop(leash, animationValue.width(), animationValue.height())
.show(leash);
mDesktopModeWindowDecoration.updateResizeVeil(t, animationValue);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/UnhandledDragController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/UnhandledDragController.kt
new file mode 100644
index 0000000..ccf48d0
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/UnhandledDragController.kt
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.draganddrop
+
+import android.os.RemoteException
+import android.util.Log
+import android.view.DragEvent
+import android.view.IWindowManager
+import android.window.IUnhandledDragCallback
+import android.window.IUnhandledDragListener
+import androidx.annotation.VisibleForTesting
+import com.android.internal.protolog.common.ProtoLog
+import com.android.wm.shell.common.ShellExecutor
+import com.android.wm.shell.protolog.ShellProtoLogGroup
+import java.util.function.Consumer
+
+/**
+ * Manages the listener and callbacks for unhandled global drags.
+ */
+class UnhandledDragController(
+ val wmService: IWindowManager,
+ mainExecutor: ShellExecutor
+) {
+ private var callback: UnhandledDragAndDropCallback? = null
+
+ private val unhandledDragListener: IUnhandledDragListener =
+ object : IUnhandledDragListener.Stub() {
+ override fun onUnhandledDrop(event: DragEvent, callback: IUnhandledDragCallback) {
+ mainExecutor.execute() {
+ this@UnhandledDragController.onUnhandledDrop(event, callback)
+ }
+ }
+ }
+
+ /**
+ * Listener called when an unhandled drag is started.
+ */
+ interface UnhandledDragAndDropCallback {
+ /**
+ * Called when a global drag is unhandled (ie. dropped outside of all visible windows, or
+ * dropped on a window that does not want to handle it).
+ *
+ * The implementer _must_ call onFinishedCallback, and if it consumes the drop, then it is
+ * also responsible for releasing up the drag surface provided via the drag event.
+ */
+ fun onUnhandledDrop(dragEvent: DragEvent, onFinishedCallback: Consumer<Boolean>) {}
+ }
+
+ /**
+ * Sets a listener for callbacks when an unhandled drag happens.
+ */
+ fun setListener(listener: UnhandledDragAndDropCallback?) {
+ val updateWm = (callback == null && listener != null)
+ || (callback != null && listener == null)
+ callback = listener
+ if (updateWm) {
+ try {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP,
+ "%s unhandled drag listener",
+ if (callback != null) "Registering" else "Unregistering")
+ wmService.setUnhandledDragListener(
+ if (callback != null) unhandledDragListener else null)
+ } catch (e: RemoteException) {
+ Log.e(TAG, "Failed to set unhandled drag listener")
+ }
+ }
+ }
+
+ @VisibleForTesting
+ fun onUnhandledDrop(dragEvent: DragEvent, wmCallback: IUnhandledDragCallback) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP,
+ "onUnhandledDrop: %s", dragEvent)
+ if (callback == null) {
+ wmCallback.notifyUnhandledDropComplete(false)
+ }
+
+ callback?.onUnhandledDrop(dragEvent) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP,
+ "Notifying onUnhandledDrop complete: %b", it)
+ wmCallback.notifyUnhandledDropComplete(it)
+ }
+ }
+
+ companion object {
+ private val TAG = UnhandledDragController::class.java.simpleName
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
index e5045ae..70b2f21 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
@@ -2959,13 +2959,17 @@
}
public void goToFullscreenFromSplit() {
- boolean leftOrTop;
- if (mSideStage.isFocused()) {
- leftOrTop = (mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT);
+ // If main stage is focused, toEnd = true if
+ // mSideStagePosition = SPLIT_POSITION_BOTTOM_OR_RIGHT. Otherwise toEnd = false
+ // If side stage is focused, toEnd = true if
+ // mSideStagePosition = SPLIT_POSITION_TOP_OR_LEFT. Otherwise toEnd = false
+ final boolean toEnd;
+ if (mMainStage.isFocused()) {
+ toEnd = (mSideStagePosition == SPLIT_POSITION_BOTTOM_OR_RIGHT);
} else {
- leftOrTop = (mSideStagePosition == SPLIT_POSITION_BOTTOM_OR_RIGHT);
+ toEnd = (mSideStagePosition == SPLIT_POSITION_TOP_OR_LEFT);
}
- mSplitLayout.flingDividerToDismiss(!leftOrTop, EXIT_REASON_FULLSCREEN_SHORTCUT);
+ mSplitLayout.flingDividerToDismiss(toEnd, EXIT_REASON_FULLSCREEN_SHORTCUT);
}
/** Move the specified task to fullscreen, regardless of focus state. */
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/UnhandledDragControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/UnhandledDragControllerTest.kt
new file mode 100644
index 0000000..522f052
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/UnhandledDragControllerTest.kt
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.draganddrop
+
+import android.os.RemoteException
+import android.view.DragEvent
+import android.view.DragEvent.ACTION_DROP
+import android.view.IWindowManager
+import android.view.SurfaceControl
+import android.window.IUnhandledDragCallback
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.wm.shell.ShellTestCase
+import com.android.wm.shell.common.ShellExecutor
+import com.android.wm.shell.draganddrop.UnhandledDragController.UnhandledDragAndDropCallback
+import java.util.function.Consumer
+import junit.framework.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers
+import org.mockito.Mock
+import org.mockito.Mockito
+import org.mockito.Mockito.mock
+import org.mockito.Mockito.reset
+import org.mockito.Mockito.verify
+import org.mockito.MockitoAnnotations
+
+/**
+ * Tests for the unhandled drag controller.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class UnhandledDragControllerTest : ShellTestCase() {
+ @Mock
+ private lateinit var mIWindowManager: IWindowManager
+
+ @Mock
+ private lateinit var mMainExecutor: ShellExecutor
+
+ private lateinit var mController: UnhandledDragController
+
+ @Before
+ @Throws(RemoteException::class)
+ fun setUp() {
+ MockitoAnnotations.initMocks(this)
+ mController = UnhandledDragController(mIWindowManager, mMainExecutor)
+ }
+
+ @Test
+ fun setListener_registersUnregistersWithWM() {
+ mController.setListener(object : UnhandledDragAndDropCallback {})
+ mController.setListener(object : UnhandledDragAndDropCallback {})
+ mController.setListener(object : UnhandledDragAndDropCallback {})
+ verify(mIWindowManager, Mockito.times(1))
+ .setUnhandledDragListener(ArgumentMatchers.any())
+
+ reset(mIWindowManager)
+ mController.setListener(null)
+ mController.setListener(null)
+ mController.setListener(null)
+ verify(mIWindowManager, Mockito.times(1))
+ .setUnhandledDragListener(ArgumentMatchers.isNull())
+ }
+
+ @Test
+ fun onUnhandledDrop_noListener_expectNotifyUnhandled() {
+ // Simulate an unhandled drop
+ val dropEvent = DragEvent.obtain(ACTION_DROP, 0f, 0f, 0f, 0f, null, null, null,
+ null, null, false)
+ val wmCallback = mock(IUnhandledDragCallback::class.java)
+ mController.onUnhandledDrop(dropEvent, wmCallback)
+
+ verify(wmCallback).notifyUnhandledDropComplete(ArgumentMatchers.eq(false))
+ }
+
+ @Test
+ fun onUnhandledDrop_withListener_expectNotifyHandled() {
+ val lastDragEvent = arrayOfNulls<DragEvent>(1)
+
+ // Set a listener to listen for unhandled drops
+ mController.setListener(object : UnhandledDragAndDropCallback {
+ override fun onUnhandledDrop(dragEvent: DragEvent,
+ onFinishedCallback: Consumer<Boolean>) {
+ lastDragEvent[0] = dragEvent
+ onFinishedCallback.accept(true)
+ dragEvent.dragSurface.release()
+ }
+ })
+
+ // Simulate an unhandled drop
+ val dragSurface = mock(SurfaceControl::class.java)
+ val dropEvent = DragEvent.obtain(ACTION_DROP, 0f, 0f, 0f, 0f, null, null, null,
+ dragSurface, null, false)
+ val wmCallback = mock(IUnhandledDragCallback::class.java)
+ mController.onUnhandledDrop(dropEvent, wmCallback)
+
+ verify(wmCallback).notifyUnhandledDropComplete(ArgumentMatchers.eq(true))
+ verify(dragSurface).release()
+ assertEquals(lastDragEvent.get(0), dropEvent)
+ }
+}
diff --git a/libs/androidfw/AssetManager2.cpp b/libs/androidfw/AssetManager2.cpp
index 8748dab..46f636e 100644
--- a/libs/androidfw/AssetManager2.cpp
+++ b/libs/androidfw/AssetManager2.cpp
@@ -117,6 +117,10 @@
return true;
}
+void AssetManager2::PresetApkAssets(ApkAssetsList apk_assets) {
+ BuildDynamicRefTable(apk_assets);
+}
+
bool AssetManager2::SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets,
bool invalidate_caches) {
return SetApkAssets(ApkAssetsList(apk_assets.begin(), apk_assets.size()), invalidate_caches);
@@ -432,13 +436,18 @@
return false;
}
-void AssetManager2::SetConfigurations(std::vector<ResTable_config> configurations) {
+void AssetManager2::SetConfigurations(std::vector<ResTable_config> configurations,
+ bool force_refresh) {
int diff = 0;
- if (configurations_.size() != configurations.size()) {
+ if (force_refresh) {
diff = -1;
} else {
- for (int i = 0; i < configurations_.size(); i++) {
- diff |= configurations_[i].diff(configurations[i]);
+ if (configurations_.size() != configurations.size()) {
+ diff = -1;
+ } else {
+ for (int i = 0; i < configurations_.size(); i++) {
+ diff |= configurations_[i].diff(configurations[i]);
+ }
}
}
configurations_ = std::move(configurations);
@@ -775,8 +784,7 @@
bool has_locale = false;
if (result->config.locale == 0) {
if (default_locale_ != 0) {
- ResTable_config conf;
- conf.locale = default_locale_;
+ ResTable_config conf = {.locale = default_locale_};
// Since we know conf has a locale and only a locale, match will tell us if that locale
// matches
has_locale = conf.match(config);
diff --git a/libs/androidfw/include/androidfw/AssetManager2.h b/libs/androidfw/include/androidfw/AssetManager2.h
index d9ff35b..17a8ba6 100644
--- a/libs/androidfw/include/androidfw/AssetManager2.h
+++ b/libs/androidfw/include/androidfw/AssetManager2.h
@@ -124,6 +124,9 @@
// new resource IDs.
bool SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches = true);
bool SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets, bool invalidate_caches = true);
+ // This one is an optimization - it skips all calculations for applying the currently set
+ // configuration, expecting a configuration update later with a forced refresh.
+ void PresetApkAssets(ApkAssetsList apk_assets);
const ApkAssetsPtr& GetApkAssets(ApkAssetsCookie cookie) const;
int GetApkAssetsCount() const {
@@ -156,7 +159,7 @@
// Sets/resets the configuration for this AssetManager. This will cause all
// caches that are related to the configuration change to be invalidated.
- void SetConfigurations(std::vector<ResTable_config> configurations);
+ void SetConfigurations(std::vector<ResTable_config> configurations, bool force_refresh = false);
inline const std::vector<ResTable_config>& GetConfigurations() const {
return configurations_;
diff --git a/libs/input/SpriteIcon.h b/libs/input/SpriteIcon.h
index 9e6cc81..0939af4 100644
--- a/libs/input/SpriteIcon.h
+++ b/libs/input/SpriteIcon.h
@@ -27,33 +27,20 @@
* Icon that a sprite displays, including its hotspot.
*/
struct SpriteIcon {
- inline SpriteIcon() : style(PointerIconStyle::TYPE_NULL), hotSpotX(0), hotSpotY(0) {}
- inline SpriteIcon(const graphics::Bitmap& bitmap, PointerIconStyle style, float hotSpotX,
- float hotSpotY, bool drawNativeDropShadow)
+ explicit SpriteIcon() = default;
+ explicit SpriteIcon(const graphics::Bitmap& bitmap, PointerIconStyle style, float hotSpotX,
+ float hotSpotY, bool drawNativeDropShadow)
: bitmap(bitmap),
style(style),
hotSpotX(hotSpotX),
hotSpotY(hotSpotY),
drawNativeDropShadow(drawNativeDropShadow) {}
- graphics::Bitmap bitmap;
- PointerIconStyle style;
- float hotSpotX;
- float hotSpotY;
- bool drawNativeDropShadow;
-
- inline SpriteIcon copy() const {
- return SpriteIcon(bitmap.copy(ANDROID_BITMAP_FORMAT_RGBA_8888), style, hotSpotX, hotSpotY,
- drawNativeDropShadow);
- }
-
- inline void reset() {
- bitmap.reset();
- style = PointerIconStyle::TYPE_NULL;
- hotSpotX = 0;
- hotSpotY = 0;
- drawNativeDropShadow = false;
- }
+ graphics::Bitmap bitmap{};
+ PointerIconStyle style{PointerIconStyle::TYPE_NULL};
+ float hotSpotX{};
+ float hotSpotY{};
+ bool drawNativeDropShadow{false};
inline bool isValid() const { return bitmap.isValid() && !bitmap.isEmpty(); }
diff --git a/media/java/android/media/flags/projection.aconfig b/media/java/android/media/flags/projection.aconfig
new file mode 100644
index 0000000..c4b38c7
--- /dev/null
+++ b/media/java/android/media/flags/projection.aconfig
@@ -0,0 +1,11 @@
+package: "com.android.media.flags"
+
+# Project link: https://gantry.corp.google.com/projects/android_platform_window_surfaces/changes
+
+flag {
+ name: "limit_manage_media_projection"
+ namespace: "lse_desktop_experience"
+ description: "Limit signature permission manage_media_projection to the SystemUI role"
+ bug: "323008518"
+ is_fixed_read_only: true
+}
diff --git a/media/java/android/media/metrics/EditingEndedEvent.java b/media/java/android/media/metrics/EditingEndedEvent.java
index 5ed8d40..f1c5c9d 100644
--- a/media/java/android/media/metrics/EditingEndedEvent.java
+++ b/media/java/android/media/metrics/EditingEndedEvent.java
@@ -20,6 +20,7 @@
import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.IntRange;
+import android.annotation.LongDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Bundle;
@@ -27,6 +28,8 @@
import android.os.Parcelable;
import java.lang.annotation.Retention;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Objects;
/** Event for an editing operation having ended. */
@@ -156,14 +159,66 @@
@SuppressWarnings("HidingField") // Hiding field from superclass as for playback events.
private final long mTimeSinceCreatedMillis;
+ private final ArrayList<MediaItemInfo> mInputMediaItemInfos;
+ @Nullable private final MediaItemInfo mOutputMediaItemInfo;
+
+ /** @hide */
+ @LongDef(
+ prefix = {"OPERATION_TYPE_"},
+ flag = true,
+ value = {
+ OPERATION_TYPE_VIDEO_TRANSCODE,
+ OPERATION_TYPE_AUDIO_TRANSCODE,
+ OPERATION_TYPE_VIDEO_EDIT,
+ OPERATION_TYPE_AUDIO_EDIT,
+ OPERATION_TYPE_VIDEO_TRANSMUX,
+ OPERATION_TYPE_AUDIO_TRANSMUX,
+ OPERATION_TYPE_PAUSED,
+ OPERATION_TYPE_RESUMED,
+ })
+ @Retention(java.lang.annotation.RetentionPolicy.SOURCE)
+ public @interface OperationType {}
+
+ /** Input video was decoded and re-encoded. */
+ public static final long OPERATION_TYPE_VIDEO_TRANSCODE = 1;
+
+ /** Input audio was decoded and re-encoded. */
+ public static final long OPERATION_TYPE_AUDIO_TRANSCODE = 1L << 1;
+
+ /** Input video was edited. */
+ public static final long OPERATION_TYPE_VIDEO_EDIT = 1L << 2;
+
+ /** Input audio was edited. */
+ public static final long OPERATION_TYPE_AUDIO_EDIT = 1L << 3;
+
+ /** Input video samples were writted (muxed) directly to the output file without transcoding. */
+ public static final long OPERATION_TYPE_VIDEO_TRANSMUX = 1L << 4;
+
+ /** Input audio samples were written (muxed) directly to the output file without transcoding. */
+ public static final long OPERATION_TYPE_AUDIO_TRANSMUX = 1L << 5;
+
+ /** The editing operation was paused before it completed. */
+ public static final long OPERATION_TYPE_PAUSED = 1L << 6;
+
+ /** The editing operation resumed a previous (paused) operation. */
+ public static final long OPERATION_TYPE_RESUMED = 1L << 7;
+
+ private final @OperationType long mOperationTypes;
+
private EditingEndedEvent(
@FinalState int finalState,
@ErrorCode int errorCode,
long timeSinceCreatedMillis,
+ ArrayList<MediaItemInfo> inputMediaItemInfos,
+ @Nullable MediaItemInfo outputMediaItemInfo,
+ @OperationType long operationTypes,
@NonNull Bundle extras) {
mFinalState = finalState;
mErrorCode = errorCode;
mTimeSinceCreatedMillis = timeSinceCreatedMillis;
+ mInputMediaItemInfos = inputMediaItemInfos;
+ mOutputMediaItemInfo = outputMediaItemInfo;
+ mOperationTypes = operationTypes;
mMetricsBundle = extras.deepCopy();
}
@@ -194,6 +249,23 @@
return mTimeSinceCreatedMillis;
}
+ /** Gets information about the input media items, or an empty list if unspecified. */
+ @NonNull
+ public List<MediaItemInfo> getInputMediaItemInfos() {
+ return new ArrayList<>(mInputMediaItemInfos);
+ }
+
+ /** Gets information about the output media item, or {@code null} if unspecified. */
+ @Nullable
+ public MediaItemInfo getOutputMediaItemInfo() {
+ return mOutputMediaItemInfo;
+ }
+
+ /** Gets a set of flags describing the types of operations performed. */
+ public @OperationType long getOperationTypes() {
+ return mOperationTypes;
+ }
+
/**
* Gets metrics-related information that is not supported by dedicated methods.
*
@@ -208,7 +280,7 @@
@Override
@NonNull
public String toString() {
- return "PlaybackErrorEvent { "
+ return "EditingEndedEvent { "
+ "finalState = "
+ mFinalState
+ ", "
@@ -217,6 +289,15 @@
+ ", "
+ "timeSinceCreatedMillis = "
+ mTimeSinceCreatedMillis
+ + ", "
+ + "inputMediaItemInfos = "
+ + mInputMediaItemInfos
+ + ", "
+ + "outputMediaItemInfo = "
+ + mOutputMediaItemInfo
+ + ", "
+ + "operationTypes = "
+ + mOperationTypes
+ " }";
}
@@ -227,12 +308,21 @@
EditingEndedEvent that = (EditingEndedEvent) o;
return mFinalState == that.mFinalState
&& mErrorCode == that.mErrorCode
+ && Objects.equals(mInputMediaItemInfos, that.mInputMediaItemInfos)
+ && Objects.equals(mOutputMediaItemInfo, that.mOutputMediaItemInfo)
+ && mOperationTypes == that.mOperationTypes
&& mTimeSinceCreatedMillis == that.mTimeSinceCreatedMillis;
}
@Override
public int hashCode() {
- return Objects.hash(mFinalState, mErrorCode, mTimeSinceCreatedMillis);
+ return Objects.hash(
+ mFinalState,
+ mErrorCode,
+ mInputMediaItemInfos,
+ mOutputMediaItemInfo,
+ mOperationTypes,
+ mTimeSinceCreatedMillis);
}
@Override
@@ -240,6 +330,9 @@
dest.writeInt(mFinalState);
dest.writeInt(mErrorCode);
dest.writeLong(mTimeSinceCreatedMillis);
+ dest.writeTypedList(mInputMediaItemInfos);
+ dest.writeTypedObject(mOutputMediaItemInfo, /* parcelableFlags= */ 0);
+ dest.writeLong(mOperationTypes);
dest.writeBundle(mMetricsBundle);
}
@@ -249,15 +342,14 @@
}
private EditingEndedEvent(@NonNull Parcel in) {
- int finalState = in.readInt();
- int errorCode = in.readInt();
- long timeSinceCreatedMillis = in.readLong();
- Bundle metricsBundle = in.readBundle();
-
- mFinalState = finalState;
- mErrorCode = errorCode;
- mTimeSinceCreatedMillis = timeSinceCreatedMillis;
- mMetricsBundle = metricsBundle;
+ mFinalState = in.readInt();
+ mErrorCode = in.readInt();
+ mTimeSinceCreatedMillis = in.readLong();
+ mInputMediaItemInfos = new ArrayList<>();
+ in.readTypedList(mInputMediaItemInfos, MediaItemInfo.CREATOR);
+ mOutputMediaItemInfo = in.readTypedObject(MediaItemInfo.CREATOR);
+ mOperationTypes = in.readLong();
+ mMetricsBundle = in.readBundle();
}
public static final @NonNull Creator<EditingEndedEvent> CREATOR =
@@ -277,8 +369,11 @@
@FlaggedApi(FLAG_ADD_MEDIA_METRICS_EDITING)
public static final class Builder {
private final @FinalState int mFinalState;
+ private final ArrayList<MediaItemInfo> mInputMediaItemInfos;
private @ErrorCode int mErrorCode;
private long mTimeSinceCreatedMillis;
+ @Nullable private MediaItemInfo mOutputMediaItemInfo;
+ private @OperationType long mOperationTypes;
private Bundle mMetricsBundle;
/**
@@ -290,6 +385,7 @@
mFinalState = finalState;
mErrorCode = ERROR_CODE_NONE;
mTimeSinceCreatedMillis = TIME_SINCE_CREATED_UNKNOWN;
+ mInputMediaItemInfos = new ArrayList<>();
mMetricsBundle = new Bundle();
}
@@ -312,20 +408,49 @@
return this;
}
+ /** Adds information about a media item that was input to the editing operation. */
+ public @NonNull Builder addInputMediaItemInfo(@NonNull MediaItemInfo mediaItemInfo) {
+ mInputMediaItemInfos.add(Objects.requireNonNull(mediaItemInfo));
+ return this;
+ }
+
+ /** Sets information about the output media item. */
+ public @NonNull Builder setOutputMediaItemInfo(@NonNull MediaItemInfo mediaItemInfo) {
+ mOutputMediaItemInfo = Objects.requireNonNull(mediaItemInfo);
+ return this;
+ }
+
+ /**
+ * Adds an operation type to the set of operations performed.
+ *
+ * @param operationType A type of operation performed as part of this editing operation.
+ */
+ public @NonNull Builder addOperationType(@OperationType long operationType) {
+ mOperationTypes |= operationType;
+ return this;
+ }
+
/**
* Sets metrics-related information that is not supported by dedicated methods.
*
* <p>Used for backwards compatibility by the metrics infrastructure.
*/
public @NonNull Builder setMetricsBundle(@NonNull Bundle metricsBundle) {
- mMetricsBundle = metricsBundle;
+ mMetricsBundle = Objects.requireNonNull(metricsBundle);
return this;
}
/** Builds an instance. */
public @NonNull EditingEndedEvent build() {
return new EditingEndedEvent(
- mFinalState, mErrorCode, mTimeSinceCreatedMillis, mMetricsBundle);
+ mFinalState,
+ mErrorCode,
+ mTimeSinceCreatedMillis,
+ mInputMediaItemInfos,
+ mOutputMediaItemInfo,
+ mOperationTypes,
+ mMetricsBundle);
}
}
+
}
diff --git a/media/java/android/media/metrics/MediaItemInfo.java b/media/java/android/media/metrics/MediaItemInfo.java
new file mode 100644
index 0000000..63dd3cc
--- /dev/null
+++ b/media/java/android/media/metrics/MediaItemInfo.java
@@ -0,0 +1,565 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.media.metrics;
+
+import static com.android.media.editing.flags.Flags.FLAG_ADD_MEDIA_METRICS_EDITING;
+
+import android.annotation.FlaggedApi;
+import android.annotation.FloatRange;
+import android.annotation.IntDef;
+import android.annotation.IntRange;
+import android.annotation.LongDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SuppressLint;
+import android.hardware.DataSpace;
+import android.media.MediaCodec;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Size;
+
+import java.lang.annotation.Retention;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+/** Represents information about a piece of media (for example, an audio or video file). */
+@FlaggedApi(FLAG_ADD_MEDIA_METRICS_EDITING)
+public final class MediaItemInfo implements Parcelable {
+
+ /** @hide */
+ @IntDef(
+ prefix = {"SOURCE_TYPE_"},
+ value = {
+ SOURCE_TYPE_UNSPECIFIED,
+ SOURCE_TYPE_GALLERY,
+ SOURCE_TYPE_CAMERA,
+ SOURCE_TYPE_EDITING_SESSION,
+ SOURCE_TYPE_LOCAL_FILE,
+ SOURCE_TYPE_REMOTE_FILE,
+ SOURCE_TYPE_REMOTE_LIVE_STREAM,
+ SOURCE_TYPE_GENERATED,
+ })
+ @Retention(java.lang.annotation.RetentionPolicy.SOURCE)
+ public @interface SourceType {}
+
+ /** The media item's source is not known. */
+ public static final int SOURCE_TYPE_UNSPECIFIED = 0;
+
+ /** The media item came from the device gallery. */
+ public static final int SOURCE_TYPE_GALLERY = 1;
+
+ /** The media item came directly from camera capture. */
+ public static final int SOURCE_TYPE_CAMERA = 2;
+
+ /** The media item was output by a previous editing session. */
+ public static final int SOURCE_TYPE_EDITING_SESSION = 3;
+
+ /** The media item is stored on the local device's file system. */
+ public static final int SOURCE_TYPE_LOCAL_FILE = 4;
+
+ /** The media item is a remote file (for example, it's loaded from an HTTP server). */
+ public static final int SOURCE_TYPE_REMOTE_FILE = 5;
+
+ /** The media item is a remotely-served live stream. */
+ public static final int SOURCE_TYPE_REMOTE_LIVE_STREAM = 6;
+
+ /** The media item was generated by another system. */
+ public static final int SOURCE_TYPE_GENERATED = 7;
+
+ /** @hide */
+ @LongDef(
+ prefix = {"DATA_TYPE_"},
+ flag = true,
+ value = {
+ DATA_TYPE_IMAGE,
+ DATA_TYPE_VIDEO,
+ DATA_TYPE_AUDIO,
+ DATA_TYPE_METADATA,
+ DATA_TYPE_DEPTH,
+ DATA_TYPE_GAIN_MAP,
+ DATA_TYPE_HIGH_FRAME_RATE,
+ DATA_TYPE_CUE_POINTS,
+ DATA_TYPE_GAPLESS,
+ DATA_TYPE_SPATIAL_AUDIO,
+ DATA_TYPE_HIGH_DYNAMIC_RANGE_VIDEO,
+ })
+ @Retention(java.lang.annotation.RetentionPolicy.SOURCE)
+ public @interface DataType {}
+
+ /** The media item includes image data. */
+ public static final long DATA_TYPE_IMAGE = 1L;
+
+ /** The media item includes video data. */
+ public static final long DATA_TYPE_VIDEO = 1L << 1;
+
+ /** The media item includes audio data. */
+ public static final long DATA_TYPE_AUDIO = 1L << 2;
+
+ /** The media item includes metadata. */
+ public static final long DATA_TYPE_METADATA = 1L << 3;
+
+ /** The media item includes depth (z-distance) information. */
+ public static final long DATA_TYPE_DEPTH = 1L << 4;
+
+ /** The media item includes gain map information (for example, an Ultra HDR gain map). */
+ public static final long DATA_TYPE_GAIN_MAP = 1L << 5;
+
+ /** The media item includes high frame rate video data. */
+ public static final long DATA_TYPE_HIGH_FRAME_RATE = 1L << 6;
+
+ /** The media item includes time-dependent speed setting metadata. */
+ public static final long DATA_TYPE_CUE_POINTS = 1L << 7;
+
+ /** The media item includes gapless audio metadata. */
+ public static final long DATA_TYPE_GAPLESS = 1L << 8;
+
+ /** The media item includes spatial audio data. */
+ public static final long DATA_TYPE_SPATIAL_AUDIO = 1L << 9;
+
+ /** The media item includes high dynamic range (HDR) video. */
+ public static final long DATA_TYPE_HIGH_DYNAMIC_RANGE_VIDEO = 1L << 10;
+
+ /** Special value for numerical fields where the value was not specified. */
+ public static final int VALUE_UNSPECIFIED = -1;
+
+ private final @SourceType int mSourceType;
+ private final @DataType long mDataTypes;
+ private final long mDurationMillis;
+ private final long mClipDurationMillis;
+ @Nullable private final String mContainerMimeType;
+ private final List<String> mSampleMimeTypes;
+ private final List<String> mCodecNames;
+ private final int mAudioSampleRateHz;
+ private final int mAudioChannelCount;
+ private final long mAudioSampleCount;
+ private final Size mVideoSize;
+ private final int mVideoDataSpace;
+ private final float mVideoFrameRate;
+ private final long mVideoSampleCount;
+
+ private MediaItemInfo(
+ @SourceType int sourceType,
+ @DataType long dataTypes,
+ long durationMillis,
+ long clipDurationMillis,
+ @Nullable String containerMimeType,
+ List<String> sampleMimeTypes,
+ List<String> codecNames,
+ int audioSampleRateHz,
+ int audioChannelCount,
+ long audioSampleCount,
+ Size videoSize,
+ int videoDataSpace,
+ float videoFrameRate,
+ long videoSampleCount) {
+ mSourceType = sourceType;
+ mDataTypes = dataTypes;
+ mDurationMillis = durationMillis;
+ mClipDurationMillis = clipDurationMillis;
+ mContainerMimeType = containerMimeType;
+ mSampleMimeTypes = sampleMimeTypes;
+ mCodecNames = codecNames;
+ mAudioSampleRateHz = audioSampleRateHz;
+ mAudioChannelCount = audioChannelCount;
+ mAudioSampleCount = audioSampleCount;
+ mVideoSize = videoSize;
+ mVideoDataSpace = videoDataSpace;
+ mVideoFrameRate = videoFrameRate;
+ mVideoSampleCount = videoSampleCount;
+ }
+
+ /**
+ * Returns where the media item came from, or {@link #SOURCE_TYPE_UNSPECIFIED} if not specified.
+ */
+ public @SourceType int getSourceType() {
+ return mSourceType;
+ }
+
+ /** Returns the data types that are present in the media item. */
+ public @DataType long getDataTypes() {
+ return mDataTypes;
+ }
+
+ /**
+ * Returns the duration of the media item, in milliseconds, or {@link #VALUE_UNSPECIFIED} if not
+ * specified.
+ */
+ public long getDurationMillis() {
+ return mDurationMillis;
+ }
+
+ /**
+ * Returns the duration of the clip taken from the media item, in milliseconds, or {@link
+ * #VALUE_UNSPECIFIED} if not specified.
+ */
+ public long getClipDurationMillis() {
+ return mClipDurationMillis;
+ }
+
+ /** Returns the MIME type of the media container, or {@code null} if unspecified. */
+ @Nullable
+ public String getContainerMimeType() {
+ return mContainerMimeType;
+ }
+
+ /**
+ * Returns the MIME types of samples stored in the media container, or an empty list if not
+ * known.
+ */
+ @NonNull
+ public List<String> getSampleMimeTypes() {
+ return new ArrayList<>(mSampleMimeTypes);
+ }
+
+ /**
+ * Returns the {@linkplain MediaCodec#getName() media codec names} for codecs that were used as
+ * part of encoding/decoding this media item, or an empty list if not known or not applicable.
+ */
+ @NonNull
+ public List<String> getCodecNames() {
+ return new ArrayList<>(mCodecNames);
+ }
+
+ /**
+ * Returns the sample rate of audio, in Hertz, or {@link #VALUE_UNSPECIFIED} if not specified.
+ */
+ public int getAudioSampleRateHz() {
+ return mAudioSampleRateHz;
+ }
+
+ /** Returns the number of audio channels, or {@link #VALUE_UNSPECIFIED} if not specified. */
+ public int getAudioChannelCount() {
+ return mAudioChannelCount;
+ }
+
+ /**
+ * Returns the number of audio frames in the item, after clipping (if applicable), or {@link
+ * #VALUE_UNSPECIFIED} if not specified.
+ */
+ public long getAudioSampleCount() {
+ return mAudioSampleCount;
+ }
+
+ /**
+ * Returns the video size, in pixels, or a {@link Size} with width and height set to {@link
+ * #VALUE_UNSPECIFIED} if not specified.
+ */
+ @NonNull
+ public Size getVideoSize() {
+ return mVideoSize;
+ }
+
+ /** Returns the {@linkplain DataSpace data space} for video, as a packed integer. */
+ @SuppressLint("MethodNameUnits") // Packed integer for an android.hardware.DataSpace.
+ public int getVideoDataSpace() {
+ return mVideoDataSpace;
+ }
+
+ /**
+ * Returns the average video frame rate, in frames per second, or {@link #VALUE_UNSPECIFIED} if
+ * not specified.
+ */
+ public float getVideoFrameRate() {
+ return mVideoFrameRate;
+ }
+
+ /**
+ * Returns the number of video frames, aftrer clipping (if applicable), or {@link
+ * #VALUE_UNSPECIFIED} if not specified.
+ */
+ public long getVideoSampleCount() {
+ return mVideoSampleCount;
+ }
+
+ /** Builder for {@link MediaItemInfo}. */
+ @FlaggedApi(FLAG_ADD_MEDIA_METRICS_EDITING)
+ public static final class Builder {
+
+ private @SourceType int mSourceType;
+ private @DataType long mDataTypes;
+ private long mDurationMillis;
+ private long mClipDurationMillis;
+ @Nullable private String mContainerMimeType;
+ private final ArrayList<String> mSampleMimeTypes;
+ private final ArrayList<String> mCodecNames;
+ private int mAudioSampleRateHz;
+ private int mAudioChannelCount;
+ private long mAudioSampleCount;
+ @Nullable private Size mVideoSize;
+ private int mVideoDataSpace;
+ private float mVideoFrameRate;
+ private long mVideoSampleCount;
+
+ /** Creates a new builder. */
+ public Builder() {
+ mSourceType = SOURCE_TYPE_UNSPECIFIED;
+ mDurationMillis = VALUE_UNSPECIFIED;
+ mClipDurationMillis = VALUE_UNSPECIFIED;
+ mSampleMimeTypes = new ArrayList<>();
+ mCodecNames = new ArrayList<>();
+ mAudioSampleRateHz = VALUE_UNSPECIFIED;
+ mAudioChannelCount = VALUE_UNSPECIFIED;
+ mAudioSampleCount = VALUE_UNSPECIFIED;
+ mVideoSize = new Size(VALUE_UNSPECIFIED, VALUE_UNSPECIFIED);
+ mVideoFrameRate = VALUE_UNSPECIFIED;
+ mVideoSampleCount = VALUE_UNSPECIFIED;
+ }
+
+ /** Sets where the media item came from. */
+ public @NonNull Builder setSourceType(@SourceType int sourceType) {
+ mSourceType = sourceType;
+ return this;
+ }
+
+ /** Adds an additional data type represented as part of the media item. */
+ public @NonNull Builder addDataType(@DataType long dataType) {
+ mDataTypes |= dataType;
+ return this;
+ }
+
+ /** Sets the duration of the media item, in milliseconds. */
+ public @NonNull Builder setDurationMillis(long durationMillis) {
+ mDurationMillis = durationMillis;
+ return this;
+ }
+
+ /** Sets the duration of the clip taken from the media item, in milliseconds. */
+ public @NonNull Builder setClipDurationMillis(long clipDurationMillis) {
+ mClipDurationMillis = clipDurationMillis;
+ return this;
+ }
+
+ /** Sets the MIME type of the media container. */
+ public @NonNull Builder setContainerMimeType(@NonNull String containerMimeType) {
+ mContainerMimeType = Objects.requireNonNull(containerMimeType);
+ return this;
+ }
+
+ /** Adds a sample MIME type stored in the media container. */
+ public @NonNull Builder addSampleMimeType(@NonNull String mimeType) {
+ mSampleMimeTypes.add(Objects.requireNonNull(mimeType));
+ return this;
+ }
+
+ /**
+ * Adds an {@linkplain MediaCodec#getName() media codec name} that was used as part of
+ * decoding/encoding this media item.
+ */
+ public @NonNull Builder addCodecName(@NonNull String codecName) {
+ mCodecNames.add(Objects.requireNonNull(codecName));
+ return this;
+ }
+
+ /** Sets the sample rate of audio, in Hertz. */
+ public @NonNull Builder setAudioSampleRateHz(@IntRange(from = 0) int audioSampleRateHz) {
+ mAudioSampleRateHz = audioSampleRateHz;
+ return this;
+ }
+
+ /** Sets the number of audio channels. */
+ public @NonNull Builder setAudioChannelCount(@IntRange(from = 0) int audioChannelCount) {
+ mAudioChannelCount = audioChannelCount;
+ return this;
+ }
+
+ /** Sets the number of audio frames in the item, after clipping (if applicable). */
+ public @NonNull Builder setAudioSampleCount(@IntRange(from = 0) long audioSampleCount) {
+ mAudioSampleCount = audioSampleCount;
+ return this;
+ }
+
+ /** Sets the video size, in pixels. */
+ public @NonNull Builder setVideoSize(@NonNull Size videoSize) {
+ mVideoSize = Objects.requireNonNull(videoSize);
+ return this;
+ }
+
+ /**
+ * Sets the {@link DataSpace} of video frames.
+ *
+ * @param videoDataSpace The data space, returned by {@link DataSpace#pack(int, int, int)}.
+ */
+ public @NonNull Builder setVideoDataSpace(int videoDataSpace) {
+ mVideoDataSpace = videoDataSpace;
+ return this;
+ }
+
+ /** Sets the average video frame rate, in frames per second. */
+ public @NonNull Builder setVideoFrameRate(@FloatRange(from = 0) float videoFrameRate) {
+ mVideoFrameRate = videoFrameRate;
+ return this;
+ }
+
+ /** Sets the number of video frames, after clipping (if applicable). */
+ public @NonNull Builder setVideoSampleCount(@IntRange(from = 0) long videoSampleCount) {
+ mVideoSampleCount = videoSampleCount;
+ return this;
+ }
+
+ /** Builds an instance. */
+ @NonNull
+ public MediaItemInfo build() {
+ return new MediaItemInfo(
+ mSourceType,
+ mDataTypes,
+ mDurationMillis,
+ mClipDurationMillis,
+ mContainerMimeType,
+ mSampleMimeTypes,
+ mCodecNames,
+ mAudioSampleRateHz,
+ mAudioChannelCount,
+ mAudioSampleCount,
+ mVideoSize,
+ mVideoDataSpace,
+ mVideoFrameRate,
+ mVideoSampleCount);
+ }
+ }
+
+ @Override
+ @NonNull
+ public String toString() {
+ return "MediaItemInfo { "
+ + "sourceType = "
+ + mSourceType
+ + ", "
+ + "dataTypes = "
+ + mDataTypes
+ + ", "
+ + "durationMillis = "
+ + mDurationMillis
+ + ", "
+ + "clipDurationMillis = "
+ + mClipDurationMillis
+ + ", "
+ + "containerMimeType = "
+ + mContainerMimeType
+ + ", "
+ + "sampleMimeTypes = "
+ + mSampleMimeTypes
+ + ", "
+ + "codecNames = "
+ + mCodecNames
+ + ", "
+ + "audioSampleRateHz = "
+ + mAudioSampleRateHz
+ + ", "
+ + "audioChannelCount = "
+ + mAudioChannelCount
+ + ", "
+ + "audioSampleCount = "
+ + mAudioSampleCount
+ + ", "
+ + "videoSize = "
+ + mVideoSize
+ + ", "
+ + "videoDataSpace = "
+ + mVideoDataSpace
+ + ", "
+ + "videoFrameRate = "
+ + mVideoFrameRate
+ + ", "
+ + "videoSampleCount = "
+ + mVideoSampleCount
+ + " }";
+ }
+
+ @Override
+ public boolean equals(@Nullable Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ MediaItemInfo that = (MediaItemInfo) o;
+ return mSourceType == that.mSourceType
+ && mDataTypes == that.mDataTypes
+ && mDurationMillis == that.mDurationMillis
+ && mClipDurationMillis == that.mClipDurationMillis
+ && Objects.equals(mContainerMimeType, that.mContainerMimeType)
+ && mSampleMimeTypes.equals(that.mSampleMimeTypes)
+ && mCodecNames.equals(that.mCodecNames)
+ && mAudioSampleRateHz == that.mAudioSampleRateHz
+ && mAudioChannelCount == that.mAudioChannelCount
+ && mAudioSampleCount == that.mAudioSampleCount
+ && Objects.equals(mVideoSize, that.mVideoSize)
+ && Objects.equals(mVideoDataSpace, that.mVideoDataSpace)
+ && mVideoFrameRate == that.mVideoFrameRate
+ && mVideoSampleCount == that.mVideoSampleCount;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mSourceType, mDataTypes);
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mSourceType);
+ dest.writeLong(mDataTypes);
+ dest.writeLong(mDurationMillis);
+ dest.writeLong(mClipDurationMillis);
+ dest.writeString(mContainerMimeType);
+ dest.writeStringList(mSampleMimeTypes);
+ dest.writeStringList(mCodecNames);
+ dest.writeInt(mAudioSampleRateHz);
+ dest.writeInt(mAudioChannelCount);
+ dest.writeLong(mAudioSampleCount);
+ dest.writeInt(mVideoSize.getWidth());
+ dest.writeInt(mVideoSize.getHeight());
+ dest.writeInt(mVideoDataSpace);
+ dest.writeFloat(mVideoFrameRate);
+ dest.writeLong(mVideoSampleCount);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ private MediaItemInfo(@NonNull Parcel in) {
+ mSourceType = in.readInt();
+ mDataTypes = in.readLong();
+ mDurationMillis = in.readLong();
+ mClipDurationMillis = in.readLong();
+ mContainerMimeType = in.readString();
+ mSampleMimeTypes = new ArrayList<>();
+ in.readStringList(mSampleMimeTypes);
+ mCodecNames = new ArrayList<>();
+ in.readStringList(mCodecNames);
+ mAudioSampleRateHz = in.readInt();
+ mAudioChannelCount = in.readInt();
+ mAudioSampleCount = in.readLong();
+ int videoSizeWidth = in.readInt();
+ int videoSizeHeight = in.readInt();
+ mVideoSize = new Size(videoSizeWidth, videoSizeHeight);
+ mVideoDataSpace = in.readInt();
+ mVideoFrameRate = in.readFloat();
+ mVideoSampleCount = in.readLong();
+ }
+
+ public static final @NonNull Creator<MediaItemInfo> CREATOR =
+ new Creator<>() {
+ @Override
+ public MediaItemInfo[] newArray(int size) {
+ return new MediaItemInfo[size];
+ }
+
+ @Override
+ public MediaItemInfo createFromParcel(@NonNull Parcel in) {
+ return new MediaItemInfo(in);
+ }
+ };
+}
diff --git a/media/java/android/media/tv/interactive/TvInteractiveAppService.java b/media/java/android/media/tv/interactive/TvInteractiveAppService.java
index eba26d4..f332f81 100755
--- a/media/java/android/media/tv/interactive/TvInteractiveAppService.java
+++ b/media/java/android/media/tv/interactive/TvInteractiveAppService.java
@@ -873,6 +873,9 @@
/**
* Called when the corresponding TV input selected to a track.
+ *
+ * If the track is deselected and no track is currently selected,
+ * trackId is an empty string.
*/
public void onTrackSelected(@TvTrackInfo.Type int type, @NonNull String trackId) {
}
@@ -1845,6 +1848,10 @@
if (DEBUG) {
Log.d(TAG, "notifyTrackSelected (type=" + type + "trackId=" + trackId + ")");
}
+ // TvInputService accepts a Null String, but onTrackSelected expects NonNull.
+ if (trackId == null) {
+ trackId = "";
+ }
onTrackSelected(type, trackId);
}
diff --git a/packages/PackageInstaller/src/com/android/packageinstaller/v2/model/UninstallRepository.kt b/packages/PackageInstaller/src/com/android/packageinstaller/v2/model/UninstallRepository.kt
index 7cc95c5..0fc1845 100644
--- a/packages/PackageInstaller/src/com/android/packageinstaller/v2/model/UninstallRepository.kt
+++ b/packages/PackageInstaller/src/com/android/packageinstaller/v2/model/UninstallRepository.kt
@@ -36,6 +36,7 @@
import android.graphics.drawable.Icon
import android.os.Build
import android.os.Bundle
+import android.os.Flags
import android.os.Process
import android.os.UserHandle
import android.os.UserManager
@@ -97,16 +98,17 @@
}
}
- if (getMaxTargetSdkVersionForUid(context, callingUid) >= Build.VERSION_CODES.P
- && !isPermissionGranted(
+ if (getMaxTargetSdkVersionForUid(context, callingUid) >= Build.VERSION_CODES.P &&
+ !isPermissionGranted(
context, Manifest.permission.REQUEST_DELETE_PACKAGES, callingUid
- )
- && !isPermissionGranted(context, Manifest.permission.DELETE_PACKAGES, callingUid)
+ ) &&
+ !isPermissionGranted(context, Manifest.permission.DELETE_PACKAGES, callingUid)
) {
Log.e(
- LOG_TAG, "Uid " + callingUid + " does not have "
- + Manifest.permission.REQUEST_DELETE_PACKAGES + " or "
- + Manifest.permission.DELETE_PACKAGES
+ LOG_TAG,
+ "Uid " + callingUid + " does not have " +
+ Manifest.permission.REQUEST_DELETE_PACKAGES + " or " +
+ Manifest.permission.DELETE_PACKAGES
)
return UninstallAborted(UninstallAborted.ABORT_REASON_GENERIC_ERROR)
}
@@ -138,8 +140,9 @@
val profiles = userManager!!.userProfiles
if (!profiles.contains(uninstalledUser)) {
Log.e(
- LOG_TAG, "User " + Process.myUserHandle() + " can't request uninstall "
- + "for user " + uninstalledUser
+ LOG_TAG,
+ "User " + Process.myUserHandle() + " can't request uninstall " +
+ "for user " + uninstalledUser
)
return UninstallAborted(UninstallAborted.ABORT_REASON_USER_NOT_ALLOWED)
}
@@ -202,9 +205,13 @@
val isSingleUser = isSingleUser()
if (isUpdate) {
- messageBuilder.append(context.getString(
- if (isSingleUser) R.string.uninstall_update_text
- else R.string.uninstall_update_text_multiuser
+ messageBuilder.append(
+ context.getString(
+ if (isSingleUser) {
+ R.string.uninstall_update_text
+ } else {
+ R.string.uninstall_update_text_multiuser
+ }
)
)
} else if (uninstallFromAllUsers && !isSingleUser) {
@@ -214,42 +221,42 @@
val customUserManager = context.createContextAsUser(uninstalledUser!!, 0)
.getSystemService(UserManager::class.java)
val userName = customUserManager!!.userName
-
- val uninstalledUserType = getUninstalledUserType(myUserHandle, uninstalledUser!!)
- val messageString: String
- when (uninstalledUserType) {
- UserManager.USER_TYPE_PROFILE_MANAGED -> {
+ var messageString = context.getString(
+ R.string.uninstall_application_text_user,
+ userName
+ )
+ if (userManager!!.isSameProfileGroup(myUserHandle, uninstalledUser!!)) {
+ if (customUserManager!!.isManagedProfile()) {
messageString = context.getString(
- R.string.uninstall_application_text_current_user_work_profile, userName
+ R.string.uninstall_application_text_current_user_work_profile, userName
)
- }
-
- UserManager.USER_TYPE_PROFILE_CLONE -> {
+ } else if (customUserManager!!.isCloneProfile()){
isClonedApp = true
messageString = context.getString(
- R.string.uninstall_application_text_current_user_clone_profile
+ R.string.uninstall_application_text_current_user_clone_profile
)
- }
-
- else -> {
+ } else if (Flags.allowPrivateProfile() && customUserManager!!.isPrivateProfile()) {
+ // TODO(b/324244123): Get these Strings from a User Property API.
messageString = context.getString(
- R.string.uninstall_application_text_user, userName
+ R.string.uninstall_application_text_current_user_private_profile
)
}
-
}
messageBuilder.append(messageString)
} else if (isCloneProfile(uninstalledUser!!)) {
isClonedApp = true
- messageBuilder.append(context.getString(
+ messageBuilder.append(
+ context.getString(
R.string.uninstall_application_text_current_user_clone_profile
)
)
- } else if (myUserHandle == UserHandle.SYSTEM
- && hasClonedInstance(targetAppInfo!!.packageName)
+ } else if (myUserHandle == UserHandle.SYSTEM &&
+ hasClonedInstance(targetAppInfo!!.packageName)
) {
- messageBuilder.append(context.getString(
- R.string.uninstall_application_text_with_clone_instance, targetAppLabel
+ messageBuilder.append(
+ context.getString(
+ R.string.uninstall_application_text_with_clone_instance,
+ targetAppLabel
)
)
} else {
@@ -296,31 +303,6 @@
return userCount == 1 || (UserManager.isHeadlessSystemUserMode() && userCount == 2)
}
- /**
- * Returns the type of the user from where an app is being uninstalled. We are concerned with
- * only USER_TYPE_PROFILE_MANAGED and USER_TYPE_PROFILE_CLONE and whether the user and profile
- * belong to the same profile group.
- */
- private fun getUninstalledUserType(
- myUserHandle: UserHandle,
- uninstalledUserHandle: UserHandle
- ): String? {
- if (!userManager!!.isSameProfileGroup(myUserHandle, uninstalledUserHandle)) {
- return null
- }
- val customUserManager = context.createContextAsUser(uninstalledUserHandle, 0)
- .getSystemService(UserManager::class.java)
- val userTypes =
- arrayOf(UserManager.USER_TYPE_PROFILE_MANAGED, UserManager.USER_TYPE_PROFILE_CLONE)
-
- for (userType in userTypes) {
- if (customUserManager!!.isUserOfType(userType)) {
- return userType
- }
- }
- return null
- }
-
private fun hasClonedInstance(packageName: String): Boolean {
// Check if clone user is present on the device.
var cloneUser: UserHandle? = null
@@ -334,8 +316,8 @@
}
// Check if another instance of given package exists in clone user profile.
return try {
- cloneUser != null
- && packageManager.getPackageUidAsUser(
+ cloneUser != null &&
+ packageManager.getPackageUidAsUser(
packageName, PackageManager.PackageInfoFlags.of(0), cloneUser.identifier
) > 0
} catch (e: PackageManager.NameNotFoundException) {
@@ -382,7 +364,9 @@
val storageStatsManager = context.getSystemService(StorageStatsManager::class.java)
try {
val stats = storageStatsManager!!.queryStatsForPackage(
- packageManager.getApplicationInfo(pkg, 0).storageUuid, pkg, user
+ packageManager.getApplicationInfo(pkg, 0).storageUuid,
+ pkg,
+ user
)
return stats.getDataBytes()
} catch (e: Exception) {
@@ -423,17 +407,24 @@
broadcastIntent.putExtra(EventResultPersister.EXTRA_ID, uninstallId)
broadcastIntent.setPackage(context.packageName)
val pendingIntent = PendingIntent.getBroadcast(
- context, uninstallId, broadcastIntent,
+ context,
+ uninstallId,
+ broadcastIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
if (!startUninstall(
- targetPackageName!!, uninstalledUser!!, pendingIntent, uninstallFromAllUsers,
+ targetPackageName!!,
+ uninstalledUser!!,
+ pendingIntent,
+ uninstallFromAllUsers,
keepData
)
) {
handleUninstallResult(
PackageInstaller.STATUS_FAILURE,
- PackageManager.DELETE_FAILED_INTERNAL_ERROR, null, 0
+ PackageManager.DELETE_FAILED_INTERNAL_ERROR,
+ null,
+ 0
)
}
}
@@ -474,9 +465,14 @@
// Caller did not want the result back. So, we either show a Toast, or a Notification.
if (status == PackageInstaller.STATUS_SUCCESS) {
- val statusMessage = if (isClonedApp) context.getString(
- R.string.uninstall_done_clone_app, targetAppLabel
- ) else context.getString(R.string.uninstall_done_app, targetAppLabel)
+ val statusMessage = if (isClonedApp) {
+ context.getString(
+ R.string.uninstall_done_clone_app,
+ targetAppLabel
+ )
+ } else {
+ context.getString(R.string.uninstall_done_app, targetAppLabel)
+ }
uninstallResult.setValue(
UninstallSuccess(activityResultCode = legacyStatus, message = statusMessage)
)
@@ -499,27 +495,32 @@
findUserOfDeviceAdmin(myUserHandle, targetPackageName!!)
if (otherBlockingUserHandle == null) {
Log.d(
- LOG_TAG, "Uninstall failed because $targetPackageName"
- + " is a device admin"
+ LOG_TAG,
+ "Uninstall failed because $targetPackageName" +
+ " is a device admin"
)
addDeviceManagerButton(context, uninstallFailedNotification)
setBigText(
- uninstallFailedNotification, context.getString(
+ uninstallFailedNotification,
+ context.getString(
R.string.uninstall_failed_device_policy_manager
)
)
} else {
Log.d(
- LOG_TAG, "Uninstall failed because $targetPackageName"
- + " is a device admin of user $otherBlockingUserHandle"
+ LOG_TAG,
+ "Uninstall failed because $targetPackageName" +
+ " is a device admin of user $otherBlockingUserHandle"
)
val userName = context.createContextAsUser(otherBlockingUserHandle, 0)
.getSystemService(UserManager::class.java)!!.userName
setBigText(
- uninstallFailedNotification, String.format(
+ uninstallFailedNotification,
+ String.format(
context.getString(
R.string.uninstall_failed_device_policy_manager_of_user
- ), userName
+ ),
+ userName
)
)
}
@@ -528,7 +529,9 @@
PackageManager.DELETE_FAILED_OWNER_BLOCKED -> {
val otherBlockingUserHandle = findBlockingUser(targetPackageName!!)
val isProfileOfOrSame = isProfileOfOrSame(
- userManager!!, myUserHandle, otherBlockingUserHandle
+ userManager!!,
+ myUserHandle,
+ otherBlockingUserHandle
)
if (isProfileOfOrSame) {
addDeviceManagerButton(context, uninstallFailedNotification)
@@ -538,15 +541,19 @@
var bigText: String? = null
if (otherBlockingUserHandle == null) {
Log.d(
- LOG_TAG, "Uninstall failed for $targetPackageName " +
+ LOG_TAG,
+ "Uninstall failed for $targetPackageName " +
"with code $status no blocking user"
)
} else if (otherBlockingUserHandle === UserHandle.SYSTEM) {
bigText = context.getString(R.string.uninstall_blocked_device_owner)
} else {
bigText = context.getString(
- if (uninstallFromAllUsers) R.string.uninstall_all_blocked_profile_owner
- else R.string.uninstall_blocked_profile_owner
+ if (uninstallFromAllUsers) {
+ R.string.uninstall_all_blocked_profile_owner
+ } else {
+ R.string.uninstall_blocked_profile_owner
+ }
)
}
bigText?.let { setBigText(uninstallFailedNotification, it) }
@@ -554,8 +561,9 @@
else -> {
Log.d(
- LOG_TAG, "Uninstall blocked for $targetPackageName"
- + " with legacy code $legacyStatus"
+ LOG_TAG,
+ "Uninstall blocked for $targetPackageName" +
+ " with legacy code $legacyStatus"
)
}
}
@@ -639,7 +647,9 @@
Icon.createWithResource(context, R.drawable.ic_settings_multiuser),
context.getString(R.string.manage_users),
PendingIntent.getActivity(
- context, 0, getUserSettingsIntent(),
+ context,
+ 0,
+ getUserSettingsIntent(),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
@@ -668,7 +678,9 @@
Icon.createWithResource(context, R.drawable.ic_lock),
context.getString(R.string.manage_device_administrators),
PendingIntent.getActivity(
- context, 0, getDeviceManagerIntent(),
+ context,
+ 0,
+ getDeviceManagerIntent(),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
@@ -706,7 +718,8 @@
context.createContextAsUser(targetUser, 0)
.packageManager.packageInstaller.uninstall(
VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST),
- flags, pendingIntent.intentSender
+ flags,
+ pendingIntent.intentSender
)
true
} catch (e: IllegalArgumentException) {
@@ -719,7 +732,8 @@
if (callback != null) {
callback!!.onUninstallComplete(
targetPackageName!!,
- PackageManager.DELETE_FAILED_ABORTED, "Cancelled by user"
+ PackageManager.DELETE_FAILED_ABORTED,
+ "Cancelled by user"
)
}
}
diff --git a/packages/SettingsLib/aconfig/settingslib.aconfig b/packages/SettingsLib/aconfig/settingslib.aconfig
index bab6781..d622eb8 100644
--- a/packages/SettingsLib/aconfig/settingslib.aconfig
+++ b/packages/SettingsLib/aconfig/settingslib.aconfig
@@ -17,3 +17,9 @@
}
}
+flag {
+ name: "bluetooth_qs_tile_dialog_auto_on_toggle"
+ namespace: "bluetooth"
+ description: "Displays the auto on toggle in the bluetooth QS tile dialog"
+ bug: "316985153"
+}
diff --git a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
index e3012cd..249fa7f 100644
--- a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
+++ b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
@@ -1621,6 +1621,7 @@
}
public static class AppEntry extends SizeInfo {
+ @VisibleForTesting String mProfileType;
@Nullable public final File apkFile;
public final long id;
public String label;
@@ -1647,11 +1648,6 @@
*/
public boolean isHomeApp;
- /**
- * Whether or not it's a cloned app .
- */
- public boolean isCloned;
-
public String getNormalizedLabel() {
if (normalizedLabel != null) {
return normalizedLabel;
@@ -1692,11 +1688,21 @@
() -> this.ensureLabelDescriptionLocked(context));
}
UserManager um = UserManager.get(context);
- this.showInPersonalTab = shouldShowInPersonalTab(um, info.uid);
UserInfo userInfo = um.getUserInfo(UserHandle.getUserId(info.uid));
- if (userInfo != null) {
- this.isCloned = userInfo.isCloneProfile();
- }
+ mProfileType = userInfo.userType;
+ this.showInPersonalTab = shouldShowInPersonalTab(um, info.uid);
+ }
+
+ public boolean isClonedProfile() {
+ return UserManager.USER_TYPE_PROFILE_CLONE.equals(mProfileType);
+ }
+
+ public boolean isManagedProfile() {
+ return UserManager.USER_TYPE_PROFILE_MANAGED.equals(mProfileType);
+ }
+
+ public boolean isPrivateProfile() {
+ return UserManager.USER_TYPE_PROFILE_PRIVATE.equals(mProfileType);
}
/**
@@ -1890,16 +1896,24 @@
};
public static final AppFilter FILTER_WORK = new AppFilter() {
- private int mCurrentUser;
@Override
- public void init() {
- mCurrentUser = ActivityManager.getCurrentUser();
- }
+ public void init() {}
@Override
public boolean filterApp(AppEntry entry) {
- return !entry.showInPersonalTab;
+ return !entry.showInPersonalTab && entry.isManagedProfile();
+ }
+ };
+
+ public static final AppFilter FILTER_PRIVATE_PROFILE = new AppFilter() {
+
+ @Override
+ public void init() {}
+
+ @Override
+ public boolean filterApp(AppEntry entry) {
+ return !entry.showInPersonalTab && entry.isPrivateProfile();
}
};
diff --git a/packages/SettingsLib/tests/integ/src/com/android/settingslib/applications/ApplicationsStateTest.java b/packages/SettingsLib/tests/integ/src/com/android/settingslib/applications/ApplicationsStateTest.java
index c5598bf..213a66e 100644
--- a/packages/SettingsLib/tests/integ/src/com/android/settingslib/applications/ApplicationsStateTest.java
+++ b/packages/SettingsLib/tests/integ/src/com/android/settingslib/applications/ApplicationsStateTest.java
@@ -22,6 +22,7 @@
import static org.mockito.Mockito.when;
import android.content.pm.ApplicationInfo;
+import android.os.UserManager;
import org.junit.Before;
import org.junit.Test;
@@ -297,11 +298,26 @@
@Test
public void testPersonalAndWorkFiltersDisplaysCorrectApps() {
mEntry.showInPersonalTab = true;
+ mEntry.mProfileType = UserManager.USER_TYPE_FULL_SYSTEM;
assertThat(ApplicationsState.FILTER_PERSONAL.filterApp(mEntry)).isTrue();
assertThat(ApplicationsState.FILTER_WORK.filterApp(mEntry)).isFalse();
mEntry.showInPersonalTab = false;
+ mEntry.mProfileType = UserManager.USER_TYPE_PROFILE_MANAGED;
assertThat(ApplicationsState.FILTER_PERSONAL.filterApp(mEntry)).isFalse();
assertThat(ApplicationsState.FILTER_WORK.filterApp(mEntry)).isTrue();
}
+
+ @Test
+ public void testPrivateProfileFilterDisplaysCorrectApps() {
+ mEntry.showInPersonalTab = true;
+ mEntry.mProfileType = UserManager.USER_TYPE_FULL_SYSTEM;
+ assertThat(ApplicationsState.FILTER_PERSONAL.filterApp(mEntry)).isTrue();
+ assertThat(ApplicationsState.FILTER_PRIVATE_PROFILE.filterApp(mEntry)).isFalse();
+
+ mEntry.showInPersonalTab = false;
+ mEntry.mProfileType = UserManager.USER_TYPE_PROFILE_PRIVATE;
+ assertThat(ApplicationsState.FILTER_PERSONAL.filterApp(mEntry)).isFalse();
+ assertThat(ApplicationsState.FILTER_PRIVATE_PROFILE.filterApp(mEntry)).isTrue();
+ }
}
diff --git a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
index e55bbec..9ecbd50 100644
--- a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
+++ b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
@@ -31,6 +31,7 @@
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
public class SettingsStateTest extends AndroidTestCase {
@@ -626,4 +627,121 @@
assertEquals(VALUE2, settingsState.getSettingLocked(INVALID_STAGED_FLAG_1).getValue());
}
}
+
+ public void testsetSettingsLockedKeepTrunkDefault() throws Exception {
+ final PrintStream os = new PrintStream(new FileOutputStream(mSettingsFile));
+ os.print(
+ "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
+ + "<settings version=\"120\">"
+ + " <setting id=\"0\" name=\"test_namespace/flag0\" "
+ + "value=\"false\" package=\"com.android.flags\" />"
+ + " <setting id=\"1\" name=\"test_namespace/flag1\" "
+ + "value=\"false\" package=\"com.android.flags\" />"
+ + " <setting id=\"2\" name=\"test_namespace/com.android.flags.flag3\" "
+ + "value=\"false\" package=\"com.android.flags\" />"
+ + " <setting id=\"3\" "
+ + "name=\"test_another_namespace/com.android.another.flags.flag0\" "
+ + "value=\"false\" package=\"com.android.another.flags\" />"
+ + "</settings>");
+ os.close();
+
+ int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
+
+ SettingsState settingsState = new SettingsState(
+ getContext(), mLock, mSettingsFile, configKey,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+
+ String prefix = "test_namespace";
+ Map<String, String> keyValues =
+ Map.of("test_namespace/flag0", "true", "test_namespace/flag2", "false");
+ String packageName = "com.android.flags";
+
+ parsed_flags flags = parsed_flags
+ .newBuilder()
+ .addParsedFlag(parsed_flag
+ .newBuilder()
+ .setPackage(packageName)
+ .setName("flag3")
+ .setNamespace(prefix)
+ .setDescription("test flag")
+ .addBug("12345678")
+ .setState(Aconfig.flag_state.DISABLED)
+ .setPermission(Aconfig.flag_permission.READ_WRITE))
+ .addParsedFlag(parsed_flag
+ .newBuilder()
+ .setPackage("com.android.another.flags")
+ .setName("flag0")
+ .setNamespace("test_another_namespace")
+ .setDescription("test flag")
+ .addBug("12345678")
+ .setState(Aconfig.flag_state.DISABLED)
+ .setPermission(Aconfig.flag_permission.READ_WRITE))
+ .build();
+
+ synchronized (mLock) {
+ settingsState.loadAconfigDefaultValues(
+ flags.toByteArray(), settingsState.getAconfigDefaultValues());
+ List<String> updates =
+ settingsState.setSettingsLocked("test_namespace/", keyValues, packageName);
+ assertEquals(3, updates.size());
+
+ SettingsState.Setting s;
+
+ s = settingsState.getSettingLocked("test_namespace/flag0");
+ assertEquals("true", s.getValue());
+
+ s = settingsState.getSettingLocked("test_namespace/flag1");
+ assertNull(s.getValue());
+
+ s = settingsState.getSettingLocked("test_namespace/flag2");
+ assertEquals("false", s.getValue());
+
+ s = settingsState.getSettingLocked("test_namespace/com.android.flags.flag3");
+ assertEquals("false", s.getValue());
+
+ s = settingsState.getSettingLocked(
+ "test_another_namespace/com.android.another.flags.flag0");
+ assertEquals("false", s.getValue());
+ }
+ }
+
+ public void testsetSettingsLockedNoTrunkDefault() throws Exception {
+ final PrintStream os = new PrintStream(new FileOutputStream(mSettingsFile));
+ os.print(
+ "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
+ + "<settings version=\"120\">"
+ + " <setting id=\"0\" name=\"test_namespace/flag0\" "
+ + "value=\"false\" package=\"com.android.flags\" />"
+ + " <setting id=\"1\" name=\"test_namespace/flag1\" "
+ + "value=\"false\" package=\"com.android.flags\" />"
+ + "</settings>");
+ os.close();
+
+ int configKey = SettingsState.makeKey(SettingsState.SETTINGS_TYPE_CONFIG, 0);
+
+ SettingsState settingsState = new SettingsState(
+ getContext(), mLock, mSettingsFile, configKey,
+ SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
+
+ Map<String, String> keyValues =
+ Map.of("test_namespace/flag0", "true", "test_namespace/flag2", "false");
+ String packageName = "com.android.flags";
+
+ synchronized (mLock) {
+ List<String> updates =
+ settingsState.setSettingsLocked("test_namespace/", keyValues, packageName);
+ assertEquals(3, updates.size());
+
+ SettingsState.Setting s;
+
+ s = settingsState.getSettingLocked("test_namespace/flag0");
+ assertEquals("true", s.getValue());
+
+ s = settingsState.getSettingLocked("test_namespace/flag1");
+ assertNull(s.getValue());
+
+ s = settingsState.getSettingLocked("test_namespace/flag2");
+ assertEquals("false", s.getValue());
+ }
+ }
}
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 84ef6e5..c086baa 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -862,6 +862,8 @@
<!-- Permission required for CTS test - CtsTelephonyProviderTestCases -->
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />
+ <uses-permission android:name="android.permission.WRITE_BLOCKED_NUMBERS" />
+ <uses-permission android:name="android.permission.READ_BLOCKED_NUMBERS" />
<uses-permission android:name="android.permission.LOG_FOREGROUND_RESOURCE_USE" />
@@ -917,6 +919,9 @@
<!-- Permissions required for CTS test - GrammaticalInflectionManagerTest -->
<uses-permission android:name="android.permission.READ_SYSTEM_GRAMMATICAL_GENDER" />
+ <!-- Permission required for CTS test - CtsPackageManagerTestCases-->
+ <uses-permission android:name="android.permission.DOMAIN_VERIFICATION_AGENT" />
+
<application
android:label="@string/app_label"
android:theme="@android:style/Theme.DeviceDefault.DayNight"
diff --git a/packages/SystemUI/accessibility/accessibilitymenu/TEST_MAPPING b/packages/SystemUI/accessibility/accessibilitymenu/TEST_MAPPING
index 2bd52b5..29a25ad 100644
--- a/packages/SystemUI/accessibility/accessibilitymenu/TEST_MAPPING
+++ b/packages/SystemUI/accessibility/accessibilitymenu/TEST_MAPPING
@@ -4,8 +4,15 @@
"name": "AccessibilityMenuServiceTests",
"options": [
{
- "include-annotation": "android.platform.test.annotations.Presubmit"
- },
+ "exclude-annotation": "android.support.test.filters.FlakyTest"
+ }
+ ]
+ }
+ ],
+ "postsubmit": [
+ {
+ "name": "AccessibilityMenuServiceTests",
+ "options": [
{
"exclude-annotation": "android.support.test.filters.FlakyTest"
}
diff --git a/packages/SystemUI/accessibility/accessibilitymenu/tests/src/com/android/systemui/accessibility/accessibilitymenu/tests/AccessibilityMenuServiceTest.java b/packages/SystemUI/accessibility/accessibilitymenu/tests/src/com/android/systemui/accessibility/accessibilitymenu/tests/AccessibilityMenuServiceTest.java
index 9d1af0e..72c1092 100644
--- a/packages/SystemUI/accessibility/accessibilitymenu/tests/src/com/android/systemui/accessibility/accessibilitymenu/tests/AccessibilityMenuServiceTest.java
+++ b/packages/SystemUI/accessibility/accessibilitymenu/tests/src/com/android/systemui/accessibility/accessibilitymenu/tests/AccessibilityMenuServiceTest.java
@@ -36,6 +36,7 @@
import android.app.KeyguardManager;
import android.app.UiAutomation;
import android.content.BroadcastReceiver;
+import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
@@ -57,6 +58,7 @@
import org.junit.After;
import org.junit.AfterClass;
+import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -330,8 +332,10 @@
AccessibilityNodeInfo assistantButton = findGridButtonInfo(getGridButtonList(),
String.valueOf(ShortcutId.ID_ASSISTANT_VALUE.ordinal()));
Intent expectedIntent = new Intent(Intent.ACTION_VOICE_COMMAND);
- String expectedPackage = expectedIntent.resolveActivity(
- sInstrumentation.getContext().getPackageManager()).getPackageName();
+ ComponentName componentName = expectedIntent.resolveActivity(
+ sInstrumentation.getContext().getPackageManager());
+ Assume.assumeNotNull(componentName);
+ String expectedPackage = componentName.getPackageName();
sUiAutomation.executeAndWaitForEvent(
() -> assistantButton.performAction(CLICK_ID),
diff --git a/packages/SystemUI/aconfig/systemui.aconfig b/packages/SystemUI/aconfig/systemui.aconfig
index 7a4e60a..56576f1 100644
--- a/packages/SystemUI/aconfig/systemui.aconfig
+++ b/packages/SystemUI/aconfig/systemui.aconfig
@@ -354,13 +354,6 @@
}
flag {
- name: "bluetooth_qs_tile_dialog_auto_on_toggle"
- namespace: "systemui"
- description: "Displays the auto on toggle in the bluetooth QS tile dialog"
- bug: "316985153"
-}
-
-flag {
name: "smartspace_relocate_to_bottom"
namespace: "systemui"
description: "Relocate Smartspace to bottom of the Lock Screen"
diff --git a/packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/loadingeffect/LoadingEffect.kt b/packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/loadingeffect/LoadingEffect.kt
new file mode 100644
index 0000000..abe1e3d
--- /dev/null
+++ b/packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/loadingeffect/LoadingEffect.kt
@@ -0,0 +1,377 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.surfaceeffects.loadingeffect
+
+import android.animation.Animator
+import android.animation.AnimatorListenerAdapter
+import android.animation.ValueAnimator
+import android.graphics.Paint
+import android.graphics.RenderEffect
+import android.view.View
+import com.android.systemui.surfaceeffects.turbulencenoise.TurbulenceNoiseAnimationConfig
+import com.android.systemui.surfaceeffects.turbulencenoise.TurbulenceNoiseShader
+
+/**
+ * Plays loading effect with the given configuration.
+ *
+ * @param baseType immutable base shader type. This is used for constructing the shader. Reconstruct
+ * the [LoadingEffect] if the base type needs to be changed.
+ * @param config immutable parameters that are used for drawing the effect.
+ * @param paintCallback triggered every frame when animation is playing. Use this to draw the effect
+ * with [Canvas.drawPaint].
+ * @param renderEffectCallback triggered every frame when animation is playing. Use this to draw the
+ * effect with [RenderEffect].
+ * @param animationStateChangedCallback triggered when the [AnimationState] changes. Optional.
+ *
+ * The client is responsible to actually draw the [Paint] or [RenderEffect] returned in the
+ * callback. Note that [View.invalidate] must be called on each callback. There are a few ways to
+ * render the effect:
+ * 1) Use [Canvas.drawPaint]. (Preferred. Significantly cheaper!)
+ * 2) Set [RenderEffect] to the [View]. (Good for chaining effects.)
+ * 3) Use [RenderNode.setRenderEffect]. (This may be least preferred, as 2 should do what you want.)
+ *
+ * <p>First approach is more performant than other ones because [RenderEffect] forces an
+ * intermediate render pass of the View to a texture to feed into it.
+ *
+ * <p>If going with the first approach, your custom [View] would look like as follow:
+ * <pre>{@code
+ * private var paint: Paint? = null
+ * // Override [View.onDraw].
+ * override fun onDraw(canvas: Canvas) {
+ * // RuntimeShader requires hardwareAcceleration.
+ * if (!canvas.isHardwareAccelerated) return
+ *
+ * paint?.let { canvas.drawPaint(it) }
+ * }
+ *
+ * // This is called [Callback.onDraw]
+ * fun draw(paint: Paint) {
+ * this.paint = paint
+ *
+ * // Must call invalidate to trigger View#onDraw
+ * invalidate()
+ * }
+ * }</pre>
+ *
+ * <p>If going with the second approach, it doesn't require an extra custom [View], and it is as
+ * simple as calling [View.setRenderEffect] followed by [View.invalidate]. You can also chain the
+ * effect with other [RenderEffect].
+ *
+ * <p>Third approach is an option, but it's more of a boilerplate so you would like to stick with
+ * the second option. If you want to go with this option for some reason, below is the example:
+ * <pre>{@code
+ * // Initialize the shader and paint to use to pass into the [Canvas].
+ * private val renderNode = RenderNode("LoadingEffect")
+ *
+ * // Override [View.onDraw].
+ * override fun onDraw(canvas: Canvas) {
+ * // RuntimeShader requires hardwareAcceleration.
+ * if (!canvas.isHardwareAccelerated) return
+ *
+ * if (renderNode.hasDisplayList()) {
+ * canvas.drawRenderNode(renderNode)
+ * }
+ * }
+ *
+ * // This is called [Callback.onDraw]
+ * fun draw(renderEffect: RenderEffect) {
+ * renderNode.setPosition(0, 0, width, height)
+ * renderNode.setRenderEffect(renderEffect)
+ *
+ * val recordingCanvas = renderNode.beginRecording()
+ * // We need at least 1 drawing instruction.
+ * recordingCanvas.drawColor(Color.TRANSPARENT)
+ * renderNode.endRecording()
+ *
+ * // Must call invalidate to trigger View#onDraw
+ * invalidate()
+ * }
+ * }</pre>
+ */
+class LoadingEffect
+private constructor(
+ baseType: TurbulenceNoiseShader.Companion.Type,
+ private val config: TurbulenceNoiseAnimationConfig,
+ private val paintCallback: PaintDrawCallback?,
+ private val renderEffectCallback: RenderEffectDrawCallback?,
+ private val animationStateChangedCallback: AnimationStateChangedCallback? = null
+) {
+ constructor(
+ baseType: TurbulenceNoiseShader.Companion.Type,
+ config: TurbulenceNoiseAnimationConfig,
+ paintCallback: PaintDrawCallback,
+ animationStateChangedCallback: AnimationStateChangedCallback? = null
+ ) : this(
+ baseType,
+ config,
+ paintCallback,
+ renderEffectCallback = null,
+ animationStateChangedCallback
+ )
+ constructor(
+ baseType: TurbulenceNoiseShader.Companion.Type,
+ config: TurbulenceNoiseAnimationConfig,
+ renderEffectCallback: RenderEffectDrawCallback,
+ animationStateChangedCallback: AnimationStateChangedCallback? = null
+ ) : this(
+ baseType,
+ config,
+ paintCallback = null,
+ renderEffectCallback,
+ animationStateChangedCallback
+ )
+
+ private val turbulenceNoiseShader: TurbulenceNoiseShader =
+ TurbulenceNoiseShader(baseType).apply { applyConfig(config) }
+ private var currentAnimator: ValueAnimator? = null
+ private var state: AnimationState = AnimationState.NOT_PLAYING
+ set(value) {
+ if (field != value) {
+ animationStateChangedCallback?.onStateChanged(field, value)
+ field = value
+ }
+ }
+
+ // We create a paint instance only if the client renders it with Paint.
+ private val paint =
+ if (paintCallback != null) {
+ Paint().apply { this.shader = turbulenceNoiseShader }
+ } else {
+ null
+ }
+
+ /** Plays LoadingEffect. */
+ fun play() {
+ if (state != AnimationState.NOT_PLAYING) {
+ return // Ignore if any of the animation is playing.
+ }
+
+ playEaseIn()
+ }
+
+ // TODO(b/237282226): Support force finish.
+ /** Finishes the main animation, which triggers the ease-out animation. */
+ fun finish() {
+ if (state == AnimationState.MAIN) {
+ // Calling Animator#end sets the animation state back to the initial state. Using pause
+ // to avoid visual artifacts.
+ currentAnimator?.pause()
+ currentAnimator = null
+
+ playEaseOut()
+ }
+ }
+
+ /** Updates the noise color dynamically. */
+ fun updateColor(newColor: Int) {
+ turbulenceNoiseShader.setColor(newColor)
+ }
+
+ /**
+ * Retrieves the noise offset x, y, z values. This is useful for replaying the animation
+ * smoothly from the last animation, by passing in the last values to the next animation.
+ */
+ fun getNoiseOffset(): Array<Float> {
+ return arrayOf(
+ turbulenceNoiseShader.noiseOffsetX,
+ turbulenceNoiseShader.noiseOffsetY,
+ turbulenceNoiseShader.noiseOffsetZ
+ )
+ }
+
+ private fun playEaseIn() {
+ if (state != AnimationState.NOT_PLAYING) {
+ return
+ }
+ state = AnimationState.EASE_IN
+
+ val animator = ValueAnimator.ofFloat(0f, 1f)
+ animator.duration = config.easeInDuration.toLong()
+
+ // Animation should start from the initial position to avoid abrupt transition.
+ val initialX = turbulenceNoiseShader.noiseOffsetX
+ val initialY = turbulenceNoiseShader.noiseOffsetY
+ val initialZ = turbulenceNoiseShader.noiseOffsetZ
+
+ animator.addUpdateListener { updateListener ->
+ val timeInSec = updateListener.currentPlayTime * MS_TO_SEC
+ val progress = updateListener.animatedValue as Float
+
+ turbulenceNoiseShader.setNoiseMove(
+ initialX + timeInSec * config.noiseMoveSpeedX,
+ initialY + timeInSec * config.noiseMoveSpeedY,
+ initialZ + timeInSec * config.noiseMoveSpeedZ
+ )
+
+ // TODO: Replace it with a better curve.
+ turbulenceNoiseShader.setOpacity(progress * config.luminosityMultiplier)
+
+ draw()
+ }
+
+ animator.addListener(
+ object : AnimatorListenerAdapter() {
+ override fun onAnimationEnd(animation: Animator) {
+ currentAnimator = null
+ playMain()
+ }
+ }
+ )
+
+ animator.start()
+ this.currentAnimator = animator
+ }
+
+ private fun playMain() {
+ if (state != AnimationState.EASE_IN) {
+ return
+ }
+ state = AnimationState.MAIN
+
+ val animator = ValueAnimator.ofFloat(0f, 1f)
+ animator.duration = config.maxDuration.toLong()
+
+ // Animation should start from the initial position to avoid abrupt transition.
+ val initialX = turbulenceNoiseShader.noiseOffsetX
+ val initialY = turbulenceNoiseShader.noiseOffsetY
+ val initialZ = turbulenceNoiseShader.noiseOffsetZ
+
+ turbulenceNoiseShader.setOpacity(config.luminosityMultiplier)
+
+ animator.addUpdateListener { updateListener ->
+ val timeInSec = updateListener.currentPlayTime * MS_TO_SEC
+ turbulenceNoiseShader.setNoiseMove(
+ initialX + timeInSec * config.noiseMoveSpeedX,
+ initialY + timeInSec * config.noiseMoveSpeedY,
+ initialZ + timeInSec * config.noiseMoveSpeedZ
+ )
+
+ draw()
+ }
+
+ animator.addListener(
+ object : AnimatorListenerAdapter() {
+ override fun onAnimationEnd(animation: Animator) {
+ currentAnimator = null
+ playEaseOut()
+ }
+ }
+ )
+
+ animator.start()
+ this.currentAnimator = animator
+ }
+
+ private fun playEaseOut() {
+ if (state != AnimationState.MAIN) {
+ return
+ }
+ state = AnimationState.EASE_OUT
+
+ val animator = ValueAnimator.ofFloat(0f, 1f)
+ animator.duration = config.easeOutDuration.toLong()
+
+ // Animation should start from the initial position to avoid abrupt transition.
+ val initialX = turbulenceNoiseShader.noiseOffsetX
+ val initialY = turbulenceNoiseShader.noiseOffsetY
+ val initialZ = turbulenceNoiseShader.noiseOffsetZ
+
+ animator.addUpdateListener { updateListener ->
+ val timeInSec = updateListener.currentPlayTime * MS_TO_SEC
+ val progress = updateListener.animatedValue as Float
+
+ turbulenceNoiseShader.setNoiseMove(
+ initialX + timeInSec * config.noiseMoveSpeedX,
+ initialY + timeInSec * config.noiseMoveSpeedY,
+ initialZ + timeInSec * config.noiseMoveSpeedZ
+ )
+
+ // TODO: Replace it with a better curve.
+ turbulenceNoiseShader.setOpacity((1f - progress) * config.luminosityMultiplier)
+
+ draw()
+ }
+
+ animator.addListener(
+ object : AnimatorListenerAdapter() {
+ override fun onAnimationEnd(animation: Animator) {
+ currentAnimator = null
+ state = AnimationState.NOT_PLAYING
+ }
+ }
+ )
+
+ animator.start()
+ this.currentAnimator = animator
+ }
+
+ private fun draw() {
+ paintCallback?.onDraw(paint!!)
+ renderEffectCallback?.onDraw(
+ RenderEffect.createRuntimeShaderEffect(turbulenceNoiseShader, "in_src")
+ )
+ }
+
+ companion object {
+ /**
+ * States of the loading effect animation.
+ *
+ * <p>The state is designed to be follow the order below: [AnimationState.EASE_IN],
+ * [AnimationState.MAIN], [AnimationState.EASE_OUT]. Note that ease in and out don't
+ * necessarily mean the acceleration and deceleration in the animation curve. They simply
+ * mean each stage of the animation. (i.e. Intro, core, and rest)
+ */
+ enum class AnimationState {
+ EASE_IN,
+ MAIN,
+ EASE_OUT,
+ NOT_PLAYING
+ }
+
+ /** Client must implement one of the draw callbacks. */
+ interface PaintDrawCallback {
+ /**
+ * A callback with a [Paint] object that contains shader info, which is triggered every
+ * frame while animation is playing. Note that the [Paint] object here is always the
+ * same instance.
+ */
+ fun onDraw(loadingPaint: Paint)
+ }
+
+ interface RenderEffectDrawCallback {
+ /**
+ * A callback with a [RenderEffect] object that contains shader info, which is triggered
+ * every frame while animation is playing. Note that the [RenderEffect] instance is
+ * different each time to update shader uniforms.
+ */
+ fun onDraw(loadingRenderEffect: RenderEffect)
+ }
+
+ /** Optional callback that is triggered when the animation state changes. */
+ interface AnimationStateChangedCallback {
+ /**
+ * A callback that's triggered when the [AnimationState] changes. Example usage is
+ * performing a cleanup when [AnimationState] becomes [NOT_PLAYING].
+ */
+ fun onStateChanged(oldState: AnimationState, newState: AnimationState) {}
+ }
+
+ private const val MS_TO_SEC = 0.001f
+
+ private val TAG = LoadingEffect::class.java.simpleName
+ }
+}
diff --git a/packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/turbulencenoise/TurbulenceNoiseShader.kt b/packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/turbulencenoise/TurbulenceNoiseShader.kt
index 30108ac..8dd90a8 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/turbulencenoise/TurbulenceNoiseShader.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/turbulencenoise/TurbulenceNoiseShader.kt
@@ -30,6 +30,7 @@
companion object {
private const val UNIFORMS =
"""
+ uniform shader in_src; // Needed to support RenderEffect.
uniform float in_gridNum;
uniform vec3 in_noiseMove;
uniform vec2 in_size;
@@ -114,6 +115,7 @@
setSize(config.width, config.height)
setLumaMatteFactors(config.lumaMatteBlendFactor, config.lumaMatteOverallBrightness)
setInverseNoiseLuminosity(config.shouldInverseNoiseLuminosity)
+ setNoiseMove(config.noiseOffsetX, config.noiseOffsetY, config.noiseOffsetZ)
}
/** Sets the number of grid for generating noise. */
diff --git a/packages/SystemUI/compose/facade/disabled/src/com/android/systemui/compose/ComposeFacade.kt b/packages/SystemUI/compose/facade/disabled/src/com/android/systemui/compose/ComposeFacade.kt
index 9a34d6f..36ab46b4 100644
--- a/packages/SystemUI/compose/facade/disabled/src/com/android/systemui/compose/ComposeFacade.kt
+++ b/packages/SystemUI/compose/facade/disabled/src/com/android/systemui/compose/ComposeFacade.kt
@@ -25,6 +25,7 @@
import com.android.systemui.bouncer.ui.BouncerDialogFactory
import com.android.systemui.bouncer.ui.viewmodel.BouncerViewModel
import com.android.systemui.communal.ui.viewmodel.BaseCommunalViewModel
+import com.android.systemui.communal.ui.viewmodel.CommunalViewModel
import com.android.systemui.communal.widgets.WidgetConfigurator
import com.android.systemui.keyboard.stickykeys.ui.viewmodel.StickyKeysIndicatorViewModel
import com.android.systemui.keyguard.shared.model.LockscreenSceneBlueprint
@@ -104,7 +105,7 @@
throwComposeUnavailableError()
}
- override fun createCommunalContainer(context: Context, viewModel: BaseCommunalViewModel): View {
+ override fun createCommunalContainer(context: Context, viewModel: CommunalViewModel): View {
throwComposeUnavailableError()
}
diff --git a/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/compose/ComposeFacade.kt b/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/compose/ComposeFacade.kt
index 51d2a03..5b6aa09 100644
--- a/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/compose/ComposeFacade.kt
+++ b/packages/SystemUI/compose/facade/enabled/src/com/android/systemui/compose/ComposeFacade.kt
@@ -40,6 +40,7 @@
import com.android.systemui.communal.ui.compose.CommunalContainer
import com.android.systemui.communal.ui.compose.CommunalHub
import com.android.systemui.communal.ui.viewmodel.BaseCommunalViewModel
+import com.android.systemui.communal.ui.viewmodel.CommunalViewModel
import com.android.systemui.communal.widgets.WidgetConfigurator
import com.android.systemui.keyboard.stickykeys.ui.view.createStickyKeyIndicatorView
import com.android.systemui.keyboard.stickykeys.ui.viewmodel.StickyKeysIndicatorViewModel
@@ -161,7 +162,7 @@
}
}
- override fun createCommunalContainer(context: Context, viewModel: BaseCommunalViewModel): View {
+ override fun createCommunalContainer(context: Context, viewModel: CommunalViewModel): View {
return ComposeView(context).apply {
setContent { PlatformTheme { CommunalContainer(viewModel = viewModel) } }
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
index 92bc1f1..bc85513 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
@@ -23,7 +23,9 @@
import com.android.compose.animation.scene.updateSceneTransitionLayoutState
import com.android.systemui.communal.shared.model.CommunalSceneKey
import com.android.systemui.communal.shared.model.ObservableCommunalTransitionState
+import com.android.systemui.communal.ui.compose.extensions.allowGestures
import com.android.systemui.communal.ui.viewmodel.BaseCommunalViewModel
+import com.android.systemui.communal.ui.viewmodel.CommunalViewModel
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.transform
@@ -51,7 +53,7 @@
@Composable
fun CommunalContainer(
modifier: Modifier = Modifier,
- viewModel: BaseCommunalViewModel,
+ viewModel: CommunalViewModel,
) {
val currentScene: SceneKey by
viewModel.currentScene
@@ -63,6 +65,7 @@
onChangeScene = { viewModel.onSceneChanged(it.toCommunalSceneKey()) },
transitions = sceneTransitions,
)
+ val touchesAllowed by viewModel.touchesAllowed.collectAsState(initial = false)
// This effect exposes the SceneTransitionLayout's observable transition state to the rest of
// the system, and unsets it when the view is disposed to avoid a memory leak.
@@ -75,7 +78,7 @@
SceneTransitionLayout(
state = sceneTransitionLayoutState,
- modifier = modifier.fillMaxSize(),
+ modifier = modifier.fillMaxSize().allowGestures(allowed = touchesAllowed),
swipeSourceDetector = FixedSizeEdgeDetector(ContainerDimensions.EdgeSwipeSize),
) {
scene(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/BiometricTestExtensions.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/BiometricTestExtensions.kt
index 72e884e..9c2791f 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/BiometricTestExtensions.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/biometrics/BiometricTestExtensions.kt
@@ -120,6 +120,7 @@
internal fun promptInfo(
logoRes: Int = -1,
logoBitmap: Bitmap? = null,
+ logoDescription: String? = null,
title: String = "title",
subtitle: String = "sub",
description: String = "desc",
@@ -132,6 +133,7 @@
val info = PromptInfo()
info.logoRes = logoRes
info.logoBitmap = logoBitmap
+ info.logoDescription = logoDescription
info.title = title
info.subtitle = subtitle
info.description = description
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
index f70b6a5..b299ca7 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
@@ -45,6 +45,7 @@
import com.android.systemui.log.logcatLogBuffer
import com.android.systemui.media.controls.ui.MediaHierarchyManager
import com.android.systemui.media.controls.ui.MediaHost
+import com.android.systemui.shade.domain.interactor.shadeInteractor
import com.android.systemui.smartspace.data.repository.FakeSmartspaceRepository
import com.android.systemui.smartspace.data.repository.fakeSmartspaceRepository
import com.android.systemui.testKosmos
@@ -102,6 +103,7 @@
testScope,
kosmos.communalInteractor,
kosmos.communalTutorialInteractor,
+ kosmos.shadeInteractor,
mediaHost,
logcatLogBuffer("CommunalViewModelTest"),
)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt
index 7242cb2..f6c0566 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/data/repository/LightRevealScrimRepositoryTest.kt
@@ -54,7 +54,7 @@
private lateinit var powerInteractor: PowerInteractor
private lateinit var underTest: LightRevealScrimRepositoryImpl
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
@Before
fun setUp() {
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
index c23ec22..bf1d76f 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
@@ -74,6 +74,8 @@
private val dozeParameters = kosmos.dozeParameters
private val underTest by lazy { kosmos.keyguardRootViewModel }
+ private val viewState = ViewStateAccessor()
+
@Before
fun setUp() {
mSetFlagsRule.enableFlags(AConfigFlags.FLAG_KEYGUARD_BOTTOM_AREA_REFACTOR)
@@ -251,7 +253,7 @@
@Test
fun alpha_idleOnHub_isZero() =
testScope.runTest {
- val alpha by collectLastValue(underTest.alpha)
+ val alpha by collectLastValue(underTest.alpha(viewState))
// Hub transition state is idle with hub open.
communalRepository.setTransitionState(
@@ -269,7 +271,7 @@
@Test
fun alpha_transitionToHub_isZero() =
testScope.runTest {
- val alpha by collectLastValue(underTest.alpha)
+ val alpha by collectLastValue(underTest.alpha(viewState))
keyguardTransitionRepository.sendTransitionSteps(
from = KeyguardState.LOCKSCREEN,
@@ -283,7 +285,7 @@
@Test
fun alpha_transitionFromHubToLockscreen_isOne() =
testScope.runTest {
- val alpha by collectLastValue(underTest.alpha)
+ val alpha by collectLastValue(underTest.alpha(viewState))
// Transition to the glanceable hub and back.
keyguardTransitionRepository.sendTransitionSteps(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt
index 0c7ce97..288c083 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerTest.kt
@@ -16,10 +16,12 @@
package com.android.systemui.statusbar.notification.collection.render
+import android.os.Build
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.dump.DumpManager
+import com.android.systemui.log.assertLogsWtf
import com.android.systemui.statusbar.notification.collection.GroupEntryBuilder
import com.android.systemui.statusbar.notification.collection.ListEntry
import com.android.systemui.statusbar.notification.collection.NotifPipeline
@@ -30,7 +32,7 @@
import com.android.systemui.util.mockito.mock
import com.android.systemui.util.mockito.withArgCaptor
import com.google.common.truth.Truth.assertThat
-import org.junit.Assert.assertThrows
+import org.junit.Assume
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@@ -116,9 +118,9 @@
underTest.setGroupExpanded(summary1, false)
// Expanding again should throw.
- assertThrows(IllegalArgumentException::class.java) {
- underTest.setGroupExpanded(summary1, true)
- }
+ // TODO(b/320238410): Remove this check when robolectric supports wtf assertions.
+ Assume.assumeFalse(Build.FINGERPRINT.contains("robolectric"))
+ assertLogsWtf { underTest.setGroupExpanded(summary1, true) }
}
@Test
diff --git a/packages/SystemUI/res/layout/biometric_prompt_constraint_layout.xml b/packages/SystemUI/res/layout/biometric_prompt_constraint_layout.xml
index a877853..0ecdcfc 100644
--- a/packages/SystemUI/res/layout/biometric_prompt_constraint_layout.xml
+++ b/packages/SystemUI/res/layout/biometric_prompt_constraint_layout.xml
@@ -13,6 +13,16 @@
android:scaleType="fitXY"
android:visibility="gone" />
+ <TextView
+ android:id="@+id/logo_description"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="@integer/biometric_dialog_text_gravity"
+ android:singleLine="true"
+ android:marqueeRepeatLimit="1"
+ android:ellipsize="marquee"
+ android:visibility="gone"/>
+
<ImageView
android:id="@+id/background"
android:layout_width="0dp"
diff --git a/packages/SystemUI/res/layout/biometric_prompt_layout.xml b/packages/SystemUI/res/layout/biometric_prompt_layout.xml
index 10f7113..e759074 100644
--- a/packages/SystemUI/res/layout/biometric_prompt_layout.xml
+++ b/packages/SystemUI/res/layout/biometric_prompt_layout.xml
@@ -28,6 +28,15 @@
android:scaleType="fitXY"/>
<TextView
+ android:id="@+id/logo_description"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="@integer/biometric_dialog_text_gravity"
+ android:singleLine="true"
+ android:marqueeRepeatLimit="1"
+ android:ellipsize="marquee"/>
+
+ <TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
diff --git a/packages/SystemUI/res/layout/bluetooth_tile_dialog.xml b/packages/SystemUI/res/layout/bluetooth_tile_dialog.xml
index a0f916c..ac781ec 100644
--- a/packages/SystemUI/res/layout/bluetooth_tile_dialog.xml
+++ b/packages/SystemUI/res/layout/bluetooth_tile_dialog.xml
@@ -81,7 +81,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="21dp"
- android:minHeight="145dp"
+ android:minHeight="@dimen/bluetooth_dialog_scroll_view_min_height"
android:fillViewport="true"
app:layout_constrainedHeight="true"
app:layout_constraintStart_toStartOf="parent"
@@ -97,11 +97,11 @@
<TextView
android:id="@+id/bluetooth_toggle_title"
android:layout_width="0dp"
- android:layout_height="64dp"
- android:maxLines="1"
+ android:layout_height="68dp"
+ android:maxLines="2"
android:ellipsize="end"
android:gravity="start|center_vertical"
- android:paddingEnd="0dp"
+ android:paddingEnd="15dp"
android:paddingStart="36dp"
android:text="@string/turn_on_bluetooth"
android:clickable="false"
@@ -114,7 +114,7 @@
<Switch
android:id="@+id/bluetooth_toggle"
android:layout_width="wrap_content"
- android:layout_height="64dp"
+ android:layout_height="68dp"
android:gravity="start|center_vertical"
android:paddingEnd="40dp"
android:contentDescription="@string/turn_on_bluetooth"
@@ -126,14 +126,79 @@
app:layout_constraintStart_toEndOf="@+id/bluetooth_toggle_title"
app:layout_constraintTop_toTopOf="parent" />
+ <androidx.constraintlayout.widget.Group
+ android:id="@+id/bluetooth_auto_on_toggle_layout"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:visibility="gone"
+ app:constraint_referenced_ids="bluetooth_auto_on_toggle_title,bluetooth_auto_on_toggle,bluetooth_auto_on_toggle_info_icon,bluetooth_auto_on_toggle_info_text" />
+
+ <TextView
+ android:id="@+id/bluetooth_auto_on_toggle_title"
+ android:layout_width="0dp"
+ android:layout_height="68dp"
+ android:layout_marginBottom="20dp"
+ android:maxLines="2"
+ android:ellipsize="end"
+ android:text="@string/turn_on_bluetooth_auto_tomorrow"
+ android:gravity="start|center_vertical"
+ android:paddingEnd="15dp"
+ android:paddingStart="36dp"
+ android:clickable="false"
+ android:textAppearance="@style/TextAppearance.Dialog.Title"
+ android:textSize="16sp"
+ app:layout_constraintEnd_toStartOf="@+id/bluetooth_auto_on_toggle"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/bluetooth_toggle_title" />
+
+ <Switch
+ android:id="@+id/bluetooth_auto_on_toggle"
+ android:layout_width="wrap_content"
+ android:layout_height="68dp"
+ android:layout_marginBottom="20dp"
+ android:gravity="start|center_vertical"
+ android:paddingEnd="40dp"
+ android:contentDescription="@string/turn_on_bluetooth_auto_tomorrow"
+ android:switchMinWidth="@dimen/settingslib_switch_track_width"
+ android:theme="@style/MainSwitch.Settingslib"
+ android:thumb="@drawable/settingslib_thumb_selector"
+ android:track="@drawable/settingslib_track_selector"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toEndOf="@+id/bluetooth_auto_on_toggle_title"
+ app:layout_constraintTop_toBottomOf="@+id/bluetooth_toggle" />
+
+ <ImageView
+ android:id="@+id/bluetooth_auto_on_toggle_info_icon"
+ android:src="@drawable/ic_info_outline"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:tint="?android:attr/textColorTertiary"
+ android:paddingStart="36dp"
+ android:layout_marginTop="20dp"
+ android:layout_marginBottom="@dimen/bluetooth_dialog_layout_margin"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/bluetooth_auto_on_toggle" />
+
+ <TextView
+ android:id="@+id/bluetooth_auto_on_toggle_info_text"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="20dp"
+ android:paddingStart="36dp"
+ android:paddingEnd="40dp"
+ android:text="@string/turn_on_bluetooth_auto_info"
+ android:textAppearance="@style/TextAppearance.Dialog.Body.Message"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@id/bluetooth_auto_on_toggle_info_icon" />
+
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/device_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/bluetooth_toggle"
- app:layout_constraintBottom_toTopOf="@+id/see_all_button" />
+ app:layout_constraintTop_toBottomOf="@+id/bluetooth_toggle" />
<Button
android:id="@+id/see_all_button"
@@ -168,12 +233,10 @@
android:background="@drawable/bluetooth_tile_dialog_bg_off"
android:layout_width="0dp"
android:layout_height="64dp"
- android:layout_marginBottom="9dp"
android:contentDescription="@string/accessibility_bluetooth_device_settings_pair_new_device"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/see_all_button"
- app:layout_constraintBottom_toTopOf="@+id/done_button"
android:drawableStart="@drawable/ic_add"
android:drawablePadding="20dp"
android:drawableTint="?android:attr/textColorPrimary"
@@ -186,11 +249,19 @@
android:ellipsize="end"
android:visibility="gone" />
+ <androidx.constraintlayout.widget.Barrier
+ android:id="@+id/barrier"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ app:barrierDirection="bottom"
+ app:constraint_referenced_ids="pair_new_device_button,bluetooth_auto_on_toggle_info_text" />
+
<Button
android:id="@+id/done_button"
style="@style/Widget.Dialog.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
+ android:layout_marginTop="9dp"
android:layout_marginBottom="@dimen/dialog_bottom_padding"
android:layout_marginEnd="@dimen/dialog_side_padding"
android:layout_marginStart="@dimen/dialog_side_padding"
@@ -200,7 +271,9 @@
android:maxLines="1"
android:text="@string/inline_done_button"
app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintBottom_toBottomOf="parent" />
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/barrier"
+ app:layout_constraintVertical_bias="1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index cc31754..7537a00 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -1717,6 +1717,10 @@
<dimen name="bluetooth_dialog_layout_margin">16dp</dimen>
<!-- The height of the bluetooth device in bluetooth dialog. -->
<dimen name="bluetooth_dialog_device_height">72dp</dimen>
+ <!-- The height of the main scroll view in bluetooth dialog. -->
+ <dimen name="bluetooth_dialog_scroll_view_min_height">145dp</dimen>
+ <!-- The height of the main scroll view in bluetooth dialog with auto on toggle. -->
+ <dimen name="bluetooth_dialog_scroll_view_min_height_with_auto_on">350dp</dimen>
<!-- Height percentage of the parent container occupied by the communal view -->
<item name="communal_source_height_percentage" format="float" type="dimen">0.80</item>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 64c6cfa..e401c71 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -669,6 +669,10 @@
<string name="accessibility_quick_settings_bluetooth_device_tap_to_disconnect">disconnect</string>
<!-- QuickSettings: Accessibility label to activate a device [CHAR LIMIT=NONE]-->
<string name="accessibility_quick_settings_bluetooth_device_tap_to_activate">activate</string>
+ <!-- QuickSettings: Bluetooth auto on tomorrow [CHAR LIMIT=NONE]-->
+ <string name="turn_on_bluetooth_auto_tomorrow">Automatically turn on again tomorrow</string>
+ <!-- QuickSettings: Bluetooth auto on info text [CHAR LIMIT=NONE]-->
+ <string name="turn_on_bluetooth_auto_info">Features like Quick Share, Find My Device, and device location use Bluetooth</string>
<!-- QuickSettings: Bluetooth secondary label for the battery level of a connected device [CHAR LIMIT=20]-->
<string name="quick_settings_bluetooth_secondary_label_battery_level"><xliff:g id="battery_level_as_percentage">%s</xliff:g> battery</string>
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
index c17c8dc..6133a51c 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequest.kt
@@ -40,6 +40,7 @@
val contentView: PromptContentView? = info.contentView
val logoRes: Int = info.logoRes
val logoBitmap: Bitmap? = info.logoBitmap
+ val logoDescription: String? = info.logoDescription
val negativeButtonText: String = info.negativeButtonText?.toString() ?: ""
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
index efad21b..31aadf5 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
@@ -95,6 +95,7 @@
view.resources.getColor(R.color.biometric_dialog_gray, view.context.theme)
val logoView = view.requireViewById<ImageView>(R.id.logo)
+ val logoDescriptionView = view.requireViewById<TextView>(R.id.logo_description)
val titleView = view.requireViewById<TextView>(R.id.title)
val subtitleView = view.requireViewById<TextView>(R.id.subtitle)
val descriptionView = view.requireViewById<TextView>(R.id.description)
@@ -104,6 +105,8 @@
// set selected to enable marquee unless a screen reader is enabled
logoView.isSelected =
!accessibilityManager.isEnabled || !accessibilityManager.isTouchExplorationEnabled
+ logoDescriptionView.isSelected =
+ !accessibilityManager.isEnabled || !accessibilityManager.isTouchExplorationEnabled
titleView.isSelected =
!accessibilityManager.isEnabled || !accessibilityManager.isTouchExplorationEnabled
subtitleView.isSelected =
@@ -165,6 +168,7 @@
}
logoView.setImageDrawable(viewModel.logo.first())
+ logoDescriptionView.text = viewModel.logoDescription.first()
titleView.text = viewModel.title.first()
subtitleView.text = viewModel.subtitle.first()
descriptionView.text = viewModel.description.first()
@@ -197,6 +201,7 @@
viewsToHideWhenSmall =
listOf(
logoView,
+ logoDescriptionView,
titleView,
subtitleView,
descriptionView,
@@ -205,6 +210,7 @@
viewsToFadeInOnSizeChange =
listOf(
logoView,
+ logoDescriptionView,
titleView,
subtitleView,
descriptionView,
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
index ef5c37ea..788991d 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
@@ -17,6 +17,7 @@
package com.android.systemui.biometrics.ui.viewmodel
import android.content.Context
+import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
@@ -280,8 +281,9 @@
it.logoBitmap != null -> BitmapDrawable(context.resources, it.logoBitmap)
else ->
try {
- context.packageManager.getApplicationIcon(it.opPackageName)
- } catch (e: PackageManager.NameNotFoundException) {
+ val info = context.getApplicationInfo(it.opPackageName)
+ context.packageManager.getApplicationIcon(info)
+ } catch (e: Exception) {
Log.w(TAG, "Cannot find icon for package " + it.opPackageName, e)
null
}
@@ -289,6 +291,25 @@
}
.distinctUntilChanged()
+ /** Logo description for the prompt. */
+ val logoDescription: Flow<String> =
+ promptSelectorInteractor.prompt
+ .map {
+ when {
+ !customBiometricPrompt() || it == null -> ""
+ it.logoDescription != null -> it.logoDescription
+ else ->
+ try {
+ val info = context.getApplicationInfo(it.opPackageName)
+ context.packageManager.getApplicationLabel(info).toString()
+ } catch (e: Exception) {
+ Log.w(TAG, "Cannot find name for package " + it.opPackageName, e)
+ ""
+ }
+ }
+ }
+ .distinctUntilChanged()
+
/** Title for the prompt. */
val title: Flow<String> =
promptSelectorInteractor.prompt.map { it?.title ?: "" }.distinctUntilChanged()
@@ -682,6 +703,12 @@
}
}
+private fun Context.getApplicationInfo(packageName: String): ApplicationInfo =
+ packageManager.getApplicationInfo(
+ packageName,
+ PackageManager.MATCH_DISABLED_COMPONENTS or PackageManager.MATCH_ANY_USER
+ )
+
/** How the fingerprint sensor was started for the prompt. */
enum class FingerprintStartMode {
/** Fingerprint sensor has not started. */
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
index 40d2d16..febfd4c 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
@@ -28,6 +28,8 @@
import com.android.systemui.media.controls.ui.MediaHost
import com.android.systemui.media.controls.ui.MediaHostState
import com.android.systemui.media.dagger.MediaModule
+import com.android.systemui.shade.domain.interactor.ShadeInteractor
+import com.android.systemui.util.kotlin.BooleanFlowOperators.not
import javax.inject.Inject
import javax.inject.Named
import kotlinx.coroutines.CoroutineScope
@@ -51,6 +53,7 @@
@Application private val scope: CoroutineScope,
private val communalInteractor: CommunalInteractor,
tutorialInteractor: CommunalTutorialInteractor,
+ shadeInteractor: ShadeInteractor,
@Named(MediaModule.COMMUNAL_HUB) mediaHost: MediaHost,
@CommunalLog logBuffer: LogBuffer,
) : BaseCommunalViewModel(communalInteractor, mediaHost) {
@@ -81,6 +84,9 @@
override val isPopupOnDismissCtaShowing: Flow<Boolean> =
_isPopupOnDismissCtaShowing.asStateFlow()
+ /** Whether touches should be disabled in communal */
+ val touchesAllowed: Flow<Boolean> = not(shadeInteractor.isAnyFullyExpanded)
+
init {
// Initialize our media host for the UMO. This only needs to happen once and must be done
// before the MediaHierarchyManager attempts to move the UMO to the hub.
@@ -114,6 +120,7 @@
}
private var delayedHidePopupJob: Job? = null
+
private fun schedulePopupHiding() {
cancelDelayedPopupHiding()
delayedHidePopupJob =
diff --git a/packages/SystemUI/src/com/android/systemui/compose/BaseComposeFacade.kt b/packages/SystemUI/src/com/android/systemui/compose/BaseComposeFacade.kt
index 9a4dfdd..4e23ecd9 100644
--- a/packages/SystemUI/src/com/android/systemui/compose/BaseComposeFacade.kt
+++ b/packages/SystemUI/src/com/android/systemui/compose/BaseComposeFacade.kt
@@ -25,6 +25,7 @@
import com.android.systemui.bouncer.ui.BouncerDialogFactory
import com.android.systemui.bouncer.ui.viewmodel.BouncerViewModel
import com.android.systemui.communal.ui.viewmodel.BaseCommunalViewModel
+import com.android.systemui.communal.ui.viewmodel.CommunalViewModel
import com.android.systemui.communal.widgets.WidgetConfigurator
import com.android.systemui.keyboard.stickykeys.ui.viewmodel.StickyKeysIndicatorViewModel
import com.android.systemui.keyguard.shared.model.LockscreenSceneBlueprint
@@ -116,7 +117,7 @@
): View
/** Creates a container that hosts the communal UI and handles gesture transitions. */
- fun createCommunalContainer(context: Context, viewModel: BaseCommunalViewModel): View
+ fun createCommunalContainer(context: Context, viewModel: CommunalViewModel): View
/** Creates a [View] that represents the Lockscreen. */
fun createLockscreen(
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/TaskFragmentComponent.kt b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/TaskFragmentComponent.kt
index 6f7dcb1..297ad84 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/TaskFragmentComponent.kt
+++ b/packages/SystemUI/src/com/android/systemui/dreams/homecontrols/TaskFragmentComponent.kt
@@ -17,7 +17,7 @@
package com.android.systemui.dreams.homecontrols
import android.app.Activity
-import android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW
+import android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN
import android.content.Intent
import android.graphics.Rect
import android.os.Binder
@@ -122,15 +122,14 @@
/** Creates the task fragment */
fun createTaskFragment() {
- val taskBounds = Rect(activity.resources.configuration.windowConfiguration.bounds)
val fragmentOptions =
TaskFragmentCreationParams.Builder(
organizer.organizerToken,
fragmentToken,
activity.activityToken!!
)
- .setInitialRelativeBounds(taskBounds)
- .setWindowingMode(WINDOWING_MODE_MULTI_WINDOW)
+ .setInitialRelativeBounds(Rect())
+ .setWindowingMode(WINDOWING_MODE_FULLSCREEN)
.build()
organizer.applyTransaction(
WindowContainerTransaction().createTaskFragment(fragmentOptions),
diff --git a/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt b/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
index 41ce3fd..83b2ee2 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
+++ b/packages/SystemUI/src/com/android/systemui/flags/FlagDependencies.kt
@@ -22,8 +22,10 @@
import com.android.server.notification.Flags.crossAppPoliteNotifications
import com.android.server.notification.Flags.politeNotifications
import com.android.server.notification.Flags.vibrateWhileUnlocked
+import com.android.systemui.Flags.FLAG_COMMUNAL_HUB
import com.android.systemui.Flags.FLAG_KEYGUARD_BOTTOM_AREA_REFACTOR
import com.android.systemui.Flags.FLAG_MIGRATE_CLOCKS_TO_BLUEPRINT
+import com.android.systemui.Flags.communalHub
import com.android.systemui.Flags.keyguardBottomAreaRefactor
import com.android.systemui.Flags.migrateClocksToBlueprint
import com.android.systemui.dagger.SysUISingleton
@@ -63,6 +65,9 @@
ComposeLockscreen.token dependsOn KeyguardShadeMigrationNssl.token
ComposeLockscreen.token dependsOn keyguardBottomAreaRefactor
ComposeLockscreen.token dependsOn migrateClocksToBlueprint
+
+ // CommunalHub dependencies
+ communalHub dependsOn KeyguardShadeMigrationNssl.token
}
private inline val politeNotifications
@@ -75,4 +80,6 @@
get() = FlagToken(FLAG_KEYGUARD_BOTTOM_AREA_REFACTOR, keyguardBottomAreaRefactor())
private inline val migrateClocksToBlueprint
get() = FlagToken(FLAG_MIGRATE_CLOCKS_TO_BLUEPRINT, migrateClocksToBlueprint())
+ private inline val communalHub
+ get() = FlagToken(FLAG_COMMUNAL_HUB, communalHub())
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt
index 9e7c70d..1b7a507 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardRootViewBinder.kt
@@ -48,6 +48,7 @@
import com.android.systemui.keyguard.ui.viewmodel.BurnInParameters
import com.android.systemui.keyguard.ui.viewmodel.KeyguardRootViewModel
import com.android.systemui.keyguard.ui.viewmodel.OccludingAppDeviceEntryMessageViewModel
+import com.android.systemui.keyguard.ui.viewmodel.ViewStateAccessor
import com.android.systemui.lifecycle.repeatWhenAttached
import com.android.systemui.plugins.FalsingManager
import com.android.systemui.plugins.clocks.ClockController
@@ -112,6 +113,10 @@
}
val burnInParams = MutableStateFlow(BurnInParameters())
+ val viewState =
+ ViewStateAccessor(
+ alpha = { view.alpha },
+ )
val disposableHandle =
view.repeatWhenAttached {
@@ -134,7 +139,7 @@
if (keyguardBottomAreaRefactor()) {
launch {
- viewModel.alpha.collect { alpha ->
+ viewModel.alpha(viewState).collect { alpha ->
view.alpha = alpha
childViews[statusViewId]?.alpha = alpha
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt
index 1144efe..f95efaa 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/preview/KeyguardPreviewRenderer.kt
@@ -43,6 +43,10 @@
import android.window.InputTransferToken
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
+import androidx.constraintlayout.widget.ConstraintSet.PARENT_ID
+import androidx.constraintlayout.widget.ConstraintSet.START
+import androidx.constraintlayout.widget.ConstraintSet.TOP
+import androidx.constraintlayout.widget.ConstraintSet.WRAP_CONTENT
import androidx.core.view.isInvisible
import com.android.keyguard.ClockEventController
import com.android.keyguard.KeyguardClockSwitch
@@ -393,7 +397,7 @@
),
)
- setUpUdfps(previewContext, rootView)
+ setUpUdfps(previewContext, if (migrateClocksToBlueprint()) keyguardRootView else rootView)
if (keyguardBottomAreaRefactor()) {
setupShortcuts(keyguardRootView)
@@ -468,15 +472,6 @@
return
}
- // Place the UDFPS view in the proper sensor location
- val fingerprintLayoutParams =
- FrameLayout.LayoutParams(sensorBounds.width(), sensorBounds.height())
- fingerprintLayoutParams.setMarginsRelative(
- sensorBounds.left,
- sensorBounds.top,
- sensorBounds.right,
- sensorBounds.bottom
- )
val finger =
LayoutInflater.from(previewContext)
.inflate(
@@ -484,7 +479,31 @@
parentView,
false,
) as View
- parentView.addView(finger, fingerprintLayoutParams)
+
+ // Place the UDFPS view in the proper sensor location
+ if (migrateClocksToBlueprint()) {
+ finger.id = R.id.lock_icon_view
+ parentView.addView(finger)
+ val cs = ConstraintSet()
+ cs.clone(parentView as ConstraintLayout)
+ cs.apply {
+ constrainWidth(R.id.lock_icon_view, sensorBounds.width())
+ constrainHeight(R.id.lock_icon_view, sensorBounds.height())
+ connect(R.id.lock_icon_view, TOP, PARENT_ID, TOP, sensorBounds.top)
+ connect(R.id.lock_icon_view, START, PARENT_ID, START, sensorBounds.left)
+ }
+ cs.applyTo(parentView)
+ } else {
+ val fingerprintLayoutParams =
+ FrameLayout.LayoutParams(sensorBounds.width(), sensorBounds.height())
+ fingerprintLayoutParams.setMarginsRelative(
+ sensorBounds.left,
+ sensorBounds.top,
+ sensorBounds.right,
+ sensorBounds.bottom
+ )
+ parentView.addView(finger, fingerprintLayoutParams)
+ }
}
private fun setUpClock(previewContext: Context, parentView: ViewGroup) {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultNotificationStackScrollLayoutSection.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultNotificationStackScrollLayoutSection.kt
index d75a72f..75132a5 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultNotificationStackScrollLayoutSection.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/DefaultNotificationStackScrollLayoutSection.kt
@@ -24,11 +24,13 @@
import androidx.constraintlayout.widget.ConstraintSet.PARENT_ID
import androidx.constraintlayout.widget.ConstraintSet.START
import androidx.constraintlayout.widget.ConstraintSet.TOP
+import com.android.systemui.Flags.centralizedStatusBarDimensRefactor
import com.android.systemui.Flags.migrateClocksToBlueprint
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.keyguard.shared.KeyguardShadeMigrationNssl
import com.android.systemui.res.R
import com.android.systemui.scene.shared.flag.SceneContainerFlags
+import com.android.systemui.shade.LargeScreenHeaderHelper
import com.android.systemui.shade.NotificationPanelView
import com.android.systemui.statusbar.notification.stack.AmbientState
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController
@@ -36,6 +38,7 @@
import com.android.systemui.statusbar.notification.stack.ui.view.SharedNotificationContainer
import com.android.systemui.statusbar.notification.stack.ui.viewmodel.NotificationStackAppearanceViewModel
import com.android.systemui.statusbar.notification.stack.ui.viewmodel.SharedNotificationContainerViewModel
+import dagger.Lazy
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
@@ -52,6 +55,7 @@
ambientState: AmbientState,
controller: NotificationStackScrollLayoutController,
notificationStackSizeCalculator: NotificationStackSizeCalculator,
+ private val largeScreenHeaderHelperLazy: Lazy<LargeScreenHeaderHelper>,
@Main mainDispatcher: CoroutineDispatcher,
) :
NotificationStackScrollLayoutSection(
@@ -74,12 +78,27 @@
val bottomMargin =
context.resources.getDimensionPixelSize(R.dimen.keyguard_status_view_bottom_margin)
if (migrateClocksToBlueprint()) {
+ val useLargeScreenHeader =
+ context.resources.getBoolean(R.bool.config_use_large_screen_shade_header)
+ val marginTopLargeScreen =
+ if (centralizedStatusBarDimensRefactor()) {
+ largeScreenHeaderHelperLazy.get().getLargeScreenHeaderHeight()
+ } else {
+ context.resources.getDimensionPixelSize(
+ R.dimen.large_screen_shade_header_height
+ )
+ }
connect(
R.id.nssl_placeholder,
TOP,
R.id.smart_space_barrier_bottom,
BOTTOM,
- bottomMargin
+ bottomMargin +
+ if (useLargeScreenHeader) {
+ marginTopLargeScreen
+ } else {
+ 0
+ }
)
} else {
connect(R.id.nssl_placeholder, TOP, R.id.keyguard_status_view, BOTTOM, bottomMargin)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeNotificationStackScrollLayoutSection.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeNotificationStackScrollLayoutSection.kt
index 756a4cc..3e35ae4 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeNotificationStackScrollLayoutSection.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/SplitShadeNotificationStackScrollLayoutSection.kt
@@ -23,13 +23,11 @@
import androidx.constraintlayout.widget.ConstraintSet.PARENT_ID
import androidx.constraintlayout.widget.ConstraintSet.START
import androidx.constraintlayout.widget.ConstraintSet.TOP
-import com.android.systemui.Flags.centralizedStatusBarDimensRefactor
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.keyguard.shared.KeyguardShadeMigrationNssl
import com.android.systemui.keyguard.ui.viewmodel.KeyguardSmartspaceViewModel
import com.android.systemui.res.R
import com.android.systemui.scene.shared.flag.SceneContainerFlags
-import com.android.systemui.shade.LargeScreenHeaderHelper
import com.android.systemui.shade.NotificationPanelView
import com.android.systemui.statusbar.notification.stack.AmbientState
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController
@@ -37,7 +35,6 @@
import com.android.systemui.statusbar.notification.stack.ui.view.SharedNotificationContainer
import com.android.systemui.statusbar.notification.stack.ui.viewmodel.NotificationStackAppearanceViewModel
import com.android.systemui.statusbar.notification.stack.ui.viewmodel.SharedNotificationContainerViewModel
-import dagger.Lazy
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
@@ -56,7 +53,6 @@
notificationStackSizeCalculator: NotificationStackSizeCalculator,
private val smartspaceViewModel: KeyguardSmartspaceViewModel,
@Main mainDispatcher: CoroutineDispatcher,
- private val largeScreenHeaderHelperLazy: Lazy<LargeScreenHeaderHelper>,
) :
NotificationStackScrollLayoutSection(
context,
@@ -75,16 +71,13 @@
return
}
constraintSet.apply {
- val splitShadeTopMargin =
- if (centralizedStatusBarDimensRefactor()) {
- largeScreenHeaderHelperLazy.get().getLargeScreenHeaderHeight()
- } else {
- context.resources.getDimensionPixelSize(
- R.dimen.large_screen_shade_header_height
- )
- }
- connect(R.id.nssl_placeholder, TOP, PARENT_ID, TOP, splitShadeTopMargin)
-
+ connect(
+ R.id.nssl_placeholder,
+ TOP,
+ PARENT_ID,
+ TOP,
+ context.resources.getDimensionPixelSize(R.dimen.keyguard_split_shade_top_margin)
+ )
connect(R.id.nssl_placeholder, START, PARENT_ID, START)
connect(R.id.nssl_placeholder, END, PARENT_ID, END)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
index ec13228..83be651 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModel.kt
@@ -60,18 +60,21 @@
private val deviceEntryInteractor: DeviceEntryInteractor,
private val dozeParameters: DozeParameters,
private val keyguardInteractor: KeyguardInteractor,
- communalInteractor: CommunalInteractor,
+ private val communalInteractor: CommunalInteractor,
keyguardTransitionInteractor: KeyguardTransitionInteractor,
private val notificationsKeyguardInteractor: NotificationsKeyguardInteractor,
- aodToLockscreenTransitionViewModel: AodToLockscreenTransitionViewModel,
- lockscreenToGoneTransitionViewModel: LockscreenToGoneTransitionViewModel,
- alternateBouncerToGoneTransitionViewModel: AlternateBouncerToGoneTransitionViewModel,
- primaryBouncerToGoneTransitionViewModel: PrimaryBouncerToGoneTransitionViewModel,
- lockscreenToGlanceableHubTransitionViewModel: LockscreenToGlanceableHubTransitionViewModel,
- glanceableHubToLockscreenTransitionViewModel: GlanceableHubToLockscreenTransitionViewModel,
- screenOffAnimationController: ScreenOffAnimationController,
+ private val aodToLockscreenTransitionViewModel: AodToLockscreenTransitionViewModel,
+ private val lockscreenToGoneTransitionViewModel: LockscreenToGoneTransitionViewModel,
+ private val alternateBouncerToGoneTransitionViewModel:
+ AlternateBouncerToGoneTransitionViewModel,
+ private val primaryBouncerToGoneTransitionViewModel: PrimaryBouncerToGoneTransitionViewModel,
+ private val lockscreenToGlanceableHubTransitionViewModel:
+ LockscreenToGlanceableHubTransitionViewModel,
+ private val glanceableHubToLockscreenTransitionViewModel:
+ GlanceableHubToLockscreenTransitionViewModel,
+ private val screenOffAnimationController: ScreenOffAnimationController,
private val aodBurnInViewModel: AodBurnInViewModel,
- aodAlphaViewModel: AodAlphaViewModel,
+ private val aodAlphaViewModel: AodAlphaViewModel,
) {
val burnInLayerVisibility: Flow<Int> =
@@ -101,8 +104,8 @@
val topClippingBounds: Flow<Int?> = keyguardInteractor.topClippingBounds
/** An observable for the alpha level for the entire keyguard root view. */
- val alpha: Flow<Float> =
- combine(
+ fun alpha(viewState: ViewStateAccessor): Flow<Float> {
+ return combine(
communalInteractor.isIdleOnCommunal,
// The transitions are mutually exclusive, so they are safe to merge to get the last
// value emitted by any of them. Do not add flows that cannot make this guarantee.
@@ -110,7 +113,7 @@
aodAlphaViewModel.alpha,
lockscreenToGlanceableHubTransitionViewModel.keyguardAlpha,
glanceableHubToLockscreenTransitionViewModel.keyguardAlpha,
- lockscreenToGoneTransitionViewModel.lockscreenAlpha,
+ lockscreenToGoneTransitionViewModel.lockscreenAlpha(viewState),
primaryBouncerToGoneTransitionViewModel.lockscreenAlpha,
alternateBouncerToGoneTransitionViewModel.lockscreenAlpha,
)
@@ -125,6 +128,7 @@
}
}
.distinctUntilChanged()
+ }
/** Specific alpha value for elements visible during [KeyguardState.LOCKSCREEN] */
val lockscreenStateAlpha: Flow<Float> = aodToLockscreenTransitionViewModel.lockscreenAlpha
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModel.kt
index d981650..15459f4 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModel.kt
@@ -16,10 +16,12 @@
package com.android.systemui.keyguard.ui.viewmodel
+import android.util.MathUtils
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.keyguard.domain.interactor.FromLockscreenTransitionInteractor
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.ui.KeyguardTransitionAnimationFlow
+import com.android.systemui.keyguard.ui.KeyguardTransitionAnimationFlow.FlowBuilder
import com.android.systemui.keyguard.ui.transitions.DeviceEntryIconTransition
import javax.inject.Inject
import kotlin.time.Duration.Companion.milliseconds
@@ -37,7 +39,7 @@
animationFlow: KeyguardTransitionAnimationFlow,
) : DeviceEntryIconTransition {
- private val transitionAnimation =
+ private val transitionAnimation: FlowBuilder =
animationFlow.setup(
duration = FromLockscreenTransitionInteractor.TO_GONE_DURATION,
from = KeyguardState.LOCKSCREEN,
@@ -52,7 +54,26 @@
onCancel = { 1f },
)
- val lockscreenAlpha: Flow<Float> = shortcutsAlpha
+ fun lockscreenAlpha(viewState: ViewStateAccessor): Flow<Float> {
+ var startAlpha: Float? = null
+ return transitionAnimation.sharedFlow(
+ duration = 200.milliseconds,
+ onStep = {
+ if (startAlpha == null) {
+ startAlpha = viewState.alpha()
+ }
+ MathUtils.lerp(startAlpha!!, 0f, it)
+ },
+ onFinish = {
+ startAlpha = null
+ 0f
+ },
+ onCancel = {
+ startAlpha = null
+ 1f
+ },
+ )
+ }
override val deviceEntryParentViewAlpha: Flow<Float> =
transitionAnimation.immediatelyTransitionTo(0f)
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/ViewStateAccessor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/ViewStateAccessor.kt
new file mode 100644
index 0000000..cb5db86
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/ViewStateAccessor.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+/** View-level state information to be shared between ui and viewmodel. */
+data class ViewStateAccessor(
+ val alpha: () -> Float = { 0f },
+ val translationY: () -> Int = { 0 },
+ val translationX: () -> Int = { 0 },
+)
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt b/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt
index 40a9b9c..13d743f 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/models/player/SeekBarViewModel.kt
@@ -141,6 +141,7 @@
if (field != value) {
field = value
checkIfPollingNeeded()
+ _data = _data.copy(listening = value)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnInteractor.kt
new file mode 100644
index 0000000..dcae088
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnInteractor.kt
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.dialog.bluetooth
+
+import android.util.Log
+import com.android.systemui.dagger.SysUISingleton
+import javax.inject.Inject
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+
+/** Interactor class responsible for interacting with the Bluetooth Auto-On feature. */
+@SysUISingleton
+class BluetoothAutoOnInteractor
+@Inject
+constructor(
+ private val bluetoothAutoOnRepository: BluetoothAutoOnRepository,
+) {
+
+ val isEnabled = bluetoothAutoOnRepository.getValue.map { it == ENABLED }.distinctUntilChanged()
+
+ /**
+ * Checks if the auto on value is present in the repository.
+ *
+ * @return `true` if a value is present (i.e, the feature is enabled by the Bluetooth server).
+ */
+ suspend fun isValuePresent(): Boolean = bluetoothAutoOnRepository.isValuePresent()
+
+ /**
+ * Sets enabled or disabled based on the provided value.
+ *
+ * @param value `true` to enable the feature, `false` to disable it.
+ */
+ suspend fun setEnabled(value: Boolean) {
+ if (!isValuePresent()) {
+ Log.e(TAG, "Trying to set toggle value while feature not available.")
+ } else {
+ val newValue = if (value) ENABLED else DISABLED
+ bluetoothAutoOnRepository.setValue(newValue)
+ }
+ }
+
+ companion object {
+ private const val TAG = "BluetoothAutoOnInteractor"
+ const val DISABLED = 0
+ const val ENABLED = 1
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnRepository.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnRepository.kt
new file mode 100644
index 0000000..e17b4d3
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnRepository.kt
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.dialog.bluetooth
+
+import android.os.UserHandle
+import android.util.Log
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.user.data.repository.UserRepository
+import com.android.systemui.util.settings.SecureSettings
+import com.android.systemui.util.settings.SettingsProxyExt.observerFlow
+import javax.inject.Inject
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.flowOn
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.flow.shareIn
+import kotlinx.coroutines.withContext
+
+/** Repository class responsible for managing the Bluetooth Auto-On feature settings. */
+// TODO(b/316822488): Handle multi-user
+@SysUISingleton
+class BluetoothAutoOnRepository
+@Inject
+constructor(
+ private val secureSettings: SecureSettings,
+ private val userRepository: UserRepository,
+ @Application private val coroutineScope: CoroutineScope,
+ @Background private val backgroundDispatcher: CoroutineDispatcher,
+) {
+ // Flow representing the auto on setting value
+ internal val getValue: Flow<Int> =
+ secureSettings
+ .observerFlow(UserHandle.USER_SYSTEM, SETTING_NAME)
+ .onStart { emit(Unit) }
+ .map {
+ if (userRepository.getSelectedUserInfo().id != UserHandle.USER_SYSTEM) {
+ Log.i(TAG, "Current user is not USER_SYSTEM. Multi-user is not supported")
+ return@map UNSET
+ }
+ secureSettings.getIntForUser(SETTING_NAME, UNSET, UserHandle.USER_SYSTEM)
+ }
+ .distinctUntilChanged()
+ .flowOn(backgroundDispatcher)
+ .shareIn(coroutineScope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0))
+
+ /**
+ * Checks if the auto on setting value is ever set for the current user.
+ *
+ * @return `true` if the setting value is not UNSET, `false` otherwise.
+ */
+ suspend fun isValuePresent(): Boolean =
+ withContext(backgroundDispatcher) {
+ if (userRepository.getSelectedUserInfo().id != UserHandle.USER_SYSTEM) {
+ Log.i(TAG, "Current user is not USER_SYSTEM. Multi-user is not supported")
+ false
+ } else {
+ secureSettings.getIntForUser(SETTING_NAME, UNSET, UserHandle.USER_SYSTEM) != UNSET
+ }
+ }
+
+ /**
+ * Sets the Bluetooth Auto-On setting value for the current user.
+ *
+ * @param value The new setting value to be applied.
+ */
+ suspend fun setValue(value: Int) {
+ withContext(backgroundDispatcher) {
+ if (userRepository.getSelectedUserInfo().id != UserHandle.USER_SYSTEM) {
+ Log.i(TAG, "Current user is not USER_SYSTEM. Multi-user is not supported")
+ } else {
+ secureSettings.putIntForUser(SETTING_NAME, value, UserHandle.USER_SYSTEM)
+ }
+ }
+ }
+
+ companion object {
+ private const val TAG = "BluetoothAutoOnRepository"
+ const val SETTING_NAME = "bluetooth_automatic_turn_on"
+ const val UNSET = -1
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialog.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialog.kt
index 1a06c38..6b53c7a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialog.kt
@@ -56,7 +56,7 @@
internal class BluetoothTileDialog
constructor(
private val bluetoothToggleInitialValue: Boolean,
- private val subtitleResIdInitialValue: Int,
+ private val initialUiProperties: BluetoothTileDialogViewModel.UiProperties,
private val cachedContentHeight: Int,
private val bluetoothTileDialogCallback: BluetoothTileDialogCallback,
@Main private val mainDispatcher: CoroutineDispatcher,
@@ -71,6 +71,10 @@
internal val bluetoothStateToggle
get() = mutableBluetoothStateToggle.asStateFlow()
+ private val mutableBluetoothAutoOnToggle: MutableStateFlow<Boolean?> = MutableStateFlow(null)
+ internal val bluetoothAutoOnToggle
+ get() = mutableBluetoothAutoOnToggle.asStateFlow()
+
private val mutableDeviceItemClick: MutableSharedFlow<DeviceItem> =
MutableSharedFlow(extraBufferCapacity = 1)
internal val deviceItemClick
@@ -89,6 +93,8 @@
private lateinit var toggleView: Switch
private lateinit var subtitleTextView: TextView
+ private lateinit var autoOnToggle: Switch
+ private lateinit var autoOnToggleView: View
private lateinit var doneButton: View
private lateinit var seeAllButton: View
private lateinit var pairNewDeviceButton: View
@@ -108,6 +114,8 @@
toggleView = requireViewById(R.id.bluetooth_toggle)
subtitleTextView = requireViewById(R.id.bluetooth_tile_dialog_subtitle) as TextView
+ autoOnToggle = requireViewById(R.id.bluetooth_auto_on_toggle)
+ autoOnToggleView = requireViewById(R.id.bluetooth_auto_on_toggle_layout)
doneButton = requireViewById(R.id.done_button)
seeAllButton = requireViewById(R.id.see_all_button)
pairNewDeviceButton = requireViewById(R.id.pair_new_device_button)
@@ -116,7 +124,7 @@
setupToggle()
setupRecyclerView()
- subtitleTextView.text = context.getString(subtitleResIdInitialValue)
+ subtitleTextView.text = context.getString(initialUiProperties.subTitleResId)
doneButton.setOnClickListener { dismiss() }
seeAllButton.setOnClickListener { bluetoothTileDialogCallback.onSeeAllClicked(it) }
pairNewDeviceButton.setOnClickListener {
@@ -124,7 +132,9 @@
}
requireViewById<View>(R.id.scroll_view).apply {
scrollViewContent = this
- layoutParams.height = cachedContentHeight
+ minimumHeight =
+ resources.getDimensionPixelSize(initialUiProperties.scrollViewMinHeightResId)
+ layoutParams.height = maxOf(cachedContentHeight, minimumHeight)
}
progressBarAnimation = requireViewById(R.id.bluetooth_tile_dialog_progress_animation)
progressBarBackground = requireViewById(R.id.bluetooth_tile_dialog_progress_background)
@@ -178,13 +188,27 @@
}
}
- internal fun onBluetoothStateUpdated(isEnabled: Boolean, subtitleResId: Int) {
+ internal fun onBluetoothStateUpdated(
+ isEnabled: Boolean,
+ uiProperties: BluetoothTileDialogViewModel.UiProperties
+ ) {
toggleView.apply {
isChecked = isEnabled
setEnabled(true)
alpha = ENABLED_ALPHA
}
- subtitleTextView.text = context.getString(subtitleResId)
+ subtitleTextView.text = context.getString(uiProperties.subTitleResId)
+ autoOnToggleView.visibility = uiProperties.autoOnToggleVisibility
+ }
+
+ internal fun onBluetoothAutoOnUpdated(isEnabled: Boolean) {
+ if (::autoOnToggle.isInitialized) {
+ autoOnToggle.apply {
+ isChecked = isEnabled
+ setEnabled(true)
+ alpha = ENABLED_ALPHA
+ }
+ }
}
private fun setupToggle() {
@@ -198,6 +222,16 @@
logger.logBluetoothState(BluetoothStateStage.USER_TOGGLED, isChecked.toString())
uiEventLogger.log(BluetoothTileDialogUiEvent.BLUETOOTH_TOGGLE_CLICKED)
}
+
+ autoOnToggleView.visibility = initialUiProperties.autoOnToggleVisibility
+ autoOnToggle.setOnCheckedChangeListener { view, isChecked ->
+ mutableBluetoothAutoOnToggle.value = isChecked
+ view.apply {
+ isEnabled = false
+ alpha = DISABLED_ALPHA
+ }
+ uiEventLogger.log(BluetoothTileDialogUiEvent.BLUETOOTH_AUTO_ON_TOGGLE_CLICKED)
+ }
}
private fun setupRecyclerView() {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogUiEvent.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogUiEvent.kt
index 86e5dde..cd52e0d 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogUiEvent.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogUiEvent.kt
@@ -31,7 +31,8 @@
@UiEvent(doc = "Saved clicked to connect") SAVED_DEVICE_CONNECT(1500),
@UiEvent(doc = "Active device clicked to disconnect") ACTIVE_DEVICE_DISCONNECT(1507),
@UiEvent(doc = "Connected other device clicked to disconnect")
- CONNECTED_OTHER_DEVICE_DISCONNECT(1508);
+ CONNECTED_OTHER_DEVICE_DISCONNECT(1508),
+ @UiEvent(doc = "The auto on toggle is clicked") BLUETOOTH_AUTO_ON_TOGGLE_CLICKED(1617);
override fun getId() = metricId
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt
index 54bb95c..5a14e5f 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModel.kt
@@ -21,9 +21,15 @@
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
+import android.view.View.GONE
+import android.view.View.VISIBLE
import android.view.ViewGroup
+import androidx.annotation.DimenRes
+import androidx.annotation.StringRes
+import androidx.annotation.VisibleForTesting
import com.android.internal.jank.InteractionJankMonitor
import com.android.internal.logging.UiEventLogger
+import com.android.settingslib.flags.Flags.bluetoothQsTileDialogAutoOnToggle
import com.android.systemui.Prefs
import com.android.systemui.animation.DialogCuj
import com.android.systemui.animation.DialogTransitionAnimator
@@ -58,6 +64,7 @@
constructor(
private val deviceItemInteractor: DeviceItemInteractor,
private val bluetoothStateInteractor: BluetoothStateInteractor,
+ private val bluetoothAutoOnInteractor: BluetoothAutoOnInteractor,
private val dialogTransitionAnimator: DialogTransitionAnimator,
private val activityStarter: ActivityStarter,
private val systemClock: SystemClock,
@@ -143,7 +150,10 @@
bluetoothStateInteractor.bluetoothStateUpdate
.filterNotNull()
.onEach {
- dialog.onBluetoothStateUpdated(it, getSubtitleResId(it))
+ dialog.onBluetoothStateUpdated(
+ it,
+ UiProperties.build(it, isAutoOnToggleFeatureAvailable())
+ )
updateDeviceItemJob?.cancel()
updateDeviceItemJob = launch {
deviceItemInteractor.updateDeviceItems(
@@ -177,6 +187,21 @@
}
.launchIn(this)
+ if (isAutoOnToggleFeatureAvailable()) {
+ // bluetoothAutoOnUpdate is emitted when bluetooth auto on on/off state is
+ // changed.
+ bluetoothAutoOnInteractor.isEnabled
+ .onEach { dialog.onBluetoothAutoOnUpdated(it) }
+ .launchIn(this)
+
+ // bluetoothAutoOnToggle is emitted when user toggles the bluetooth auto on
+ // switch, send the new value to the bluetoothAutoOnInteractor.
+ dialog.bluetoothAutoOnToggle
+ .filterNotNull()
+ .onEach { bluetoothAutoOnInteractor.setEnabled(it) }
+ .launchIn(this)
+ }
+
produce<Unit> { awaitClose { dialog.cancel() } }
}
}
@@ -192,7 +217,10 @@
return BluetoothTileDialog(
bluetoothStateInteractor.isBluetoothEnabled,
- getSubtitleResId(bluetoothStateInteractor.isBluetoothEnabled),
+ UiProperties.build(
+ bluetoothStateInteractor.isBluetoothEnabled,
+ isAutoOnToggleFeatureAvailable()
+ ),
cachedContentHeight,
this@BluetoothTileDialogViewModel,
mainDispatcher,
@@ -244,6 +272,10 @@
}
}
+ @VisibleForTesting
+ internal suspend fun isAutoOnToggleFeatureAvailable() =
+ bluetoothQsTileDialogAutoOnToggle() && bluetoothAutoOnInteractor.isValuePresent()
+
companion object {
private const val INTERACTION_JANK_TAG = "bluetooth_tile_dialog"
private const val CONTENT_HEIGHT_PREF_KEY = Prefs.Key.BLUETOOTH_TILE_DIALOG_CONTENT_HEIGHT
@@ -251,6 +283,29 @@
if (isBluetoothEnabled) R.string.quick_settings_bluetooth_tile_subtitle
else R.string.bt_is_off
}
+
+ internal data class UiProperties(
+ @StringRes val subTitleResId: Int,
+ val autoOnToggleVisibility: Int,
+ @DimenRes val scrollViewMinHeightResId: Int,
+ ) {
+ companion object {
+ internal fun build(
+ isBluetoothEnabled: Boolean,
+ isAutoOnToggleFeatureAvailable: Boolean
+ ) =
+ UiProperties(
+ subTitleResId = getSubtitleResId(isBluetoothEnabled),
+ autoOnToggleVisibility =
+ if (isAutoOnToggleFeatureAvailable && !isBluetoothEnabled) VISIBLE
+ else GONE,
+ scrollViewMinHeightResId =
+ if (isAutoOnToggleFeatureAvailable)
+ R.dimen.bluetooth_dialog_scroll_view_min_height_with_auto_on
+ else R.dimen.bluetooth_dialog_scroll_view_min_height
+ )
+ }
+ }
}
internal interface BluetoothTileDialogCallback {
diff --git a/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt b/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt
index 98c0217..2f0fc51 100644
--- a/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt
+++ b/packages/SystemUI/src/com/android/systemui/sensorprivacy/SensorUseStartedActivity.kt
@@ -23,7 +23,6 @@
import android.content.DialogInterface.BUTTON_POSITIVE
import android.content.Intent
import android.content.Intent.EXTRA_PACKAGE_NAME
-import android.content.pm.PackageManager
import android.hardware.SensorPrivacyManager
import android.hardware.SensorPrivacyManager.EXTRA_ALL_SENSORS
import android.hardware.SensorPrivacyManager.EXTRA_SENSOR
@@ -32,7 +31,6 @@
import android.os.Handler
import android.window.OnBackInvokedDispatcher
import androidx.annotation.OpenForTesting
-import com.android.internal.camera.flags.Flags
import com.android.internal.util.FrameworkStatsLog.PRIVACY_TOGGLE_DIALOG_INTERACTION
import com.android.internal.util.FrameworkStatsLog.PRIVACY_TOGGLE_DIALOG_INTERACTION__ACTION__CANCEL
import com.android.internal.util.FrameworkStatsLog.PRIVACY_TOGGLE_DIALOG_INTERACTION__ACTION__ENABLE
@@ -92,14 +90,14 @@
sensor = ALL_SENSORS
val callback = IndividualSensorPrivacyController.Callback { _, _ ->
if (!sensorPrivacyController.isSensorBlocked(MICROPHONE) &&
- !isCameraBlocked(sensorUsePackageName)) {
+ !sensorPrivacyController.isSensorBlocked(CAMERA)) {
finish()
}
}
sensorPrivacyListener = callback
sensorPrivacyController.addCallback(callback)
if (!sensorPrivacyController.isSensorBlocked(MICROPHONE) &&
- !isCameraBlocked(sensorUsePackageName)) {
+ !sensorPrivacyController.isSensorBlocked(CAMERA)) {
finish()
return
}
@@ -112,22 +110,14 @@
}
val callback = IndividualSensorPrivacyController.Callback {
whichSensor: Int, isBlocked: Boolean ->
- if (whichSensor != sensor) {
- // Ignore a callback; we're not interested in.
- } else if ((whichSensor == CAMERA) && !isCameraBlocked(sensorUsePackageName)) {
- finish()
- } else if ((whichSensor == MICROPHONE) && !isBlocked) {
+ if (whichSensor == sensor && !isBlocked) {
finish()
}
}
sensorPrivacyListener = callback
sensorPrivacyController.addCallback(callback)
- if ((sensor == CAMERA) && !isCameraBlocked(sensorUsePackageName)) {
- finish()
- return
- } else if ((sensor == MICROPHONE) &&
- !sensorPrivacyController.isSensorBlocked(MICROPHONE)) {
+ if (!sensorPrivacyController.isSensorBlocked(sensor)) {
finish()
return
}
@@ -214,22 +204,6 @@
recreate()
}
- private fun isAutomotive(): Boolean {
- return getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)
- }
-
- private fun isCameraBlocked(packageName: String): Boolean {
- if (Flags.privacyAllowlist()) {
- if (isAutomotive()) {
- return sensorPrivacyController.isCameraPrivacyEnabled(packageName)
- } else {
- return sensorPrivacyController.isSensorBlocked(CAMERA)
- }
- } else {
- return sensorPrivacyController.isSensorBlocked(CAMERA)
- }
- }
-
private fun disableSensorPrivacy() {
if (sensor == ALL_SENSORS) {
sensorPrivacyController.setSensorBlocked(DIALOG, MICROPHONE, false)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/RemoteInputNotificationRebuilder.java b/packages/SystemUI/src/com/android/systemui/statusbar/RemoteInputNotificationRebuilder.java
index 90abec1..80c3551 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/RemoteInputNotificationRebuilder.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/RemoteInputNotificationRebuilder.java
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar;
+import static android.app.Flags.lifetimeExtensionRefactor;
+
import android.annotation.NonNull;
import android.app.Notification;
import android.app.RemoteInputHistoryItem;
@@ -29,6 +31,7 @@
import com.android.systemui.dagger.SysUISingleton;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;
@@ -68,7 +71,7 @@
@NonNull
public StatusBarNotification rebuildForCanceledSmartReplies(
NotificationEntry entry) {
- return rebuildWithRemoteInputInserted(entry, null /* remoteInputTest */,
+ return rebuildWithRemoteInputInserted(entry, null /* remoteInputText */,
false /* showSpinner */, null /* mimeType */, null /* uri */);
}
@@ -97,22 +100,50 @@
StatusBarNotification rebuildWithRemoteInputInserted(NotificationEntry entry,
CharSequence remoteInputText, boolean showSpinner, String mimeType, Uri uri) {
StatusBarNotification sbn = entry.getSbn();
-
Notification.Builder b = Notification.Builder
.recoverBuilder(mContext, sbn.getNotification().clone());
- if (remoteInputText != null || uri != null) {
- RemoteInputHistoryItem newItem = uri != null
- ? new RemoteInputHistoryItem(mimeType, uri, remoteInputText)
- : new RemoteInputHistoryItem(remoteInputText);
+
+ if (lifetimeExtensionRefactor()) {
+ if (entry.remoteInputs == null) {
+ entry.remoteInputs = new ArrayList<RemoteInputHistoryItem>();
+ }
+
+ // Append new remote input information to remoteInputs list
+ if (remoteInputText != null || uri != null) {
+ RemoteInputHistoryItem newItem = uri != null
+ ? new RemoteInputHistoryItem(mimeType, uri, remoteInputText)
+ : new RemoteInputHistoryItem(remoteInputText);
+ // The list is latest-first, so new elements should be added as the first element.
+ entry.remoteInputs.add(0, newItem);
+ }
+
+ // Read the whole remoteInputs list from the entry, then append all of those to the sbn.
Parcelable[] oldHistoryItems = sbn.getNotification().extras
.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS);
+
RemoteInputHistoryItem[] newHistoryItems = oldHistoryItems != null
? Stream.concat(
- Stream.of(newItem),
- Arrays.stream(oldHistoryItems).map(p -> (RemoteInputHistoryItem) p))
+ entry.remoteInputs.stream(),
+ Arrays.stream(oldHistoryItems).map(p -> (RemoteInputHistoryItem) p))
.toArray(RemoteInputHistoryItem[]::new)
- : new RemoteInputHistoryItem[] { newItem };
+ : entry.remoteInputs.toArray(RemoteInputHistoryItem[]::new);
b.setRemoteInputHistory(newHistoryItems);
+
+ } else {
+ if (remoteInputText != null || uri != null) {
+ RemoteInputHistoryItem newItem = uri != null
+ ? new RemoteInputHistoryItem(mimeType, uri, remoteInputText)
+ : new RemoteInputHistoryItem(remoteInputText);
+ Parcelable[] oldHistoryItems = sbn.getNotification().extras
+ .getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS);
+ RemoteInputHistoryItem[] newHistoryItems = oldHistoryItems != null
+ ? Stream.concat(
+ Stream.of(newItem),
+ Arrays.stream(oldHistoryItems).map(p -> (RemoteInputHistoryItem) p))
+ .toArray(RemoteInputHistoryItem[]::new)
+ : new RemoteInputHistoryItem[]{newItem};
+ b.setRemoteInputHistory(newHistoryItems);
+ }
}
b.setShowRemoteInputSpinner(showSpinner);
b.setHideSmartReplies(true);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
index cdacb10..8678f0a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
@@ -40,6 +40,7 @@
import android.app.NotificationManager.Policy;
import android.app.Person;
import android.app.RemoteInput;
+import android.app.RemoteInputHistoryItem;
import android.content.Context;
import android.content.pm.ShortcutInfo;
import android.net.Uri;
@@ -127,6 +128,7 @@
public int targetSdk;
private long lastFullScreenIntentLaunchTime = NOT_LAUNCHED_YET;
public CharSequence remoteInputText;
+ public List<RemoteInputHistoryItem> remoteInputs = null;
public String remoteInputMimeType;
public Uri remoteInputUri;
public ContentInfo remoteInputAttachment;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinator.kt
index 918bf08..28fff15 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinator.kt
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar.notification.collection.coordinator
+import android.app.Flags.lifetimeExtensionRefactor
+import android.app.Notification.FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY
import android.os.Handler
import android.service.notification.NotificationListenerService.REASON_CANCEL
import android.service.notification.NotificationListenerService.REASON_CLICK
@@ -88,11 +90,21 @@
override fun attach(pipeline: NotifPipeline) {
mNotificationRemoteInputManager.setRemoteInputListener(this)
- mRemoteInputLifetimeExtenders.forEach { pipeline.addNotificationLifetimeExtender(it) }
+ if (lifetimeExtensionRefactor()) {
+ pipeline.addNotificationLifetimeExtender(mRemoteInputActiveExtender)
+ } else {
+ mRemoteInputLifetimeExtenders.forEach {
+ pipeline.addNotificationLifetimeExtender(it)
+ }
+ }
mNotifUpdater = pipeline.getInternalNotifUpdater(TAG)
pipeline.addCollectionListener(mCollectionListener)
}
+ /*
+ * Listener that updates the appearance of the notification if it has been lifetime extended
+ * by a a direct reply or a smart reply, and cancelled.
+ */
val mCollectionListener = object : NotifCollectionListener {
override fun onEntryUpdated(entry: NotificationEntry, fromSystem: Boolean) {
if (DEBUG) {
@@ -100,9 +112,32 @@
" fromSystem=$fromSystem)")
}
if (fromSystem) {
- // Mark smart replies as sent whenever a notification is updated by the app,
- // otherwise the smart replies are never marked as sent.
- mSmartReplyController.stopSending(entry)
+ if (lifetimeExtensionRefactor()) {
+ if ((entry.getSbn().getNotification().flags
+ and FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY) > 0) {
+ if (mNotificationRemoteInputManager.shouldKeepForRemoteInputHistory(
+ entry)) {
+ val newSbn = mRebuilder.rebuildForRemoteInputReply(entry)
+ entry.onRemoteInputInserted()
+ mNotifUpdater.onInternalNotificationUpdate(newSbn,
+ "Extending lifetime of notification with remote input")
+ } else if (mNotificationRemoteInputManager.shouldKeepForSmartReplyHistory(
+ entry)) {
+ val newSbn = mRebuilder.rebuildForCanceledSmartReplies(entry)
+ mSmartReplyController.stopSending(entry)
+ mNotifUpdater.onInternalNotificationUpdate(newSbn,
+ "Extending lifetime of notification with smart reply")
+ }
+ } else {
+ // Notifications updated without FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY
+ // should have their remote inputs list cleared.
+ entry.remoteInputs = null
+ }
+ } else {
+ // Mark smart replies as sent whenever a notification is updated by the app,
+ // otherwise the smart replies are never marked as sent.
+ mSmartReplyController.stopSending(entry)
+ }
}
}
@@ -130,8 +165,10 @@
// NOTE: This is some trickery! By removing the lifetime extensions when we know they should
// be immediately re-upped, we ensure that the side-effects of the lifetime extenders get to
// fire again, thus ensuring that we add subsequent replies to the notification.
- mRemoteInputHistoryExtender.endLifetimeExtension(entry.key)
- mSmartReplyHistoryExtender.endLifetimeExtension(entry.key)
+ if (!lifetimeExtensionRefactor()) {
+ mRemoteInputHistoryExtender.endLifetimeExtension(entry.key)
+ mSmartReplyHistoryExtender.endLifetimeExtension(entry.key)
+ }
// If we're extending for remote input being active, then from the apps point of
// view it is already canceled, so we'll need to cancel it on the apps behalf
@@ -160,15 +197,19 @@
}
override fun isNotificationKeptForRemoteInputHistory(key: String) =
+ if (!lifetimeExtensionRefactor()) {
mRemoteInputHistoryExtender.isExtending(key) ||
mSmartReplyHistoryExtender.isExtending(key)
+ } else false
override fun releaseNotificationIfKeptForRemoteInputHistory(entry: NotificationEntry) {
if (DEBUG) Log.d(TAG, "releaseNotificationIfKeptForRemoteInputHistory(entry=${entry.key})")
- mRemoteInputHistoryExtender.endLifetimeExtensionAfterDelay(entry.key,
- REMOTE_INPUT_EXTENDER_RELEASE_DELAY)
- mSmartReplyHistoryExtender.endLifetimeExtensionAfterDelay(entry.key,
- REMOTE_INPUT_EXTENDER_RELEASE_DELAY)
+ if (!lifetimeExtensionRefactor()) {
+ mRemoteInputHistoryExtender.endLifetimeExtensionAfterDelay(entry.key,
+ REMOTE_INPUT_EXTENDER_RELEASE_DELAY)
+ mSmartReplyHistoryExtender.endLifetimeExtensionAfterDelay(entry.key,
+ REMOTE_INPUT_EXTENDER_RELEASE_DELAY)
+ }
mRemoteInputActiveExtender.endLifetimeExtensionAfterDelay(entry.key,
REMOTE_INPUT_EXTENDER_RELEASE_DELAY)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java
index 3cdb2cd..d1aff80 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/GroupExpansionManagerImpl.java
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar.notification.collection.render;
+import android.util.Log;
+
import androidx.annotation.NonNull;
import com.android.systemui.Dumpable;
@@ -40,6 +42,8 @@
*/
@SysUISingleton
public class GroupExpansionManagerImpl implements GroupExpansionManager, Dumpable {
+ private static final String TAG = "GroupExpansionaManagerImpl";
+
private final DumpManager mDumpManager;
private final GroupMembershipManager mGroupMembershipManager;
private final Set<OnGroupExpansionChangeListener> mOnGroupChangeListeners = new HashSet<>();
@@ -100,7 +104,7 @@
NotificationEntry groupSummary = mGroupMembershipManager.getGroupSummary(entry);
if (entry.getParent() == null) {
if (expanded) {
- throw new IllegalArgumentException("Cannot expand group that is not attached");
+ Log.wtf(TAG, "Cannot expand group that is not attached");
} else {
// The entry is no longer attached, but we still want to make sure we don't have
// a stale expansion state.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
index 47daf49..830b8c1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
@@ -1335,6 +1335,10 @@
}
}
+ public float getAlpha() {
+ return mView.getAlpha();
+ }
+
public void setSuppressChildrenMeasureAndLayout(boolean suppressLayout) {
mView.suppressChildrenMeasureAndLayout(suppressLayout);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt
index b4f578f..ffab9ea 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/view/SharedNotificationContainer.kt
@@ -76,14 +76,10 @@
}
val nsslId = R.id.notification_stack_scroller
constraintSet.apply {
- connect(nsslId, START, startConstraintId, START)
- connect(nsslId, END, PARENT_ID, END)
- connect(nsslId, BOTTOM, PARENT_ID, BOTTOM)
- connect(nsslId, TOP, PARENT_ID, TOP)
- setMargin(nsslId, START, marginStart)
- setMargin(nsslId, END, marginEnd)
- setMargin(nsslId, TOP, marginTop)
- setMargin(nsslId, BOTTOM, marginBottom)
+ connect(nsslId, START, startConstraintId, START, marginStart)
+ connect(nsslId, END, PARENT_ID, END, marginEnd)
+ connect(nsslId, BOTTOM, PARENT_ID, BOTTOM, marginBottom)
+ connect(nsslId, TOP, PARENT_ID, TOP, marginTop)
}
constraintSet.applyTo(this)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt
index 97db9b6..daea8af 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewbinder/SharedNotificationContainerBinder.kt
@@ -24,6 +24,7 @@
import androidx.lifecycle.repeatOnLifecycle
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.keyguard.ui.viewmodel.BurnInParameters
+import com.android.systemui.keyguard.ui.viewmodel.ViewStateAccessor
import com.android.systemui.lifecycle.repeatWhenAttached
import com.android.systemui.scene.shared.flag.SceneContainerFlags
import com.android.systemui.statusbar.notification.footer.shared.FooterViewRefactor
@@ -75,6 +76,10 @@
}
val burnInParams = MutableStateFlow(BurnInParameters())
+ val viewState =
+ ViewStateAccessor(
+ alpha = { controller.getAlpha() },
+ )
/*
* For animation sensitive coroutines, immediately run just like applicationScope does
@@ -141,7 +146,7 @@
if (!sceneContainerFlags.isEnabled()) {
launch {
- viewModel.expansionAlpha.collect {
+ viewModel.expansionAlpha(viewState).collect {
controller.setMaxAlphaForExpansion(it)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt
index 811da51..ff00cb3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModel.kt
@@ -50,6 +50,7 @@
import com.android.systemui.keyguard.ui.viewmodel.LockscreenToOccludedTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.OccludedToLockscreenTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToGoneTransitionViewModel
+import com.android.systemui.keyguard.ui.viewmodel.ViewStateAccessor
import com.android.systemui.shade.domain.interactor.ShadeInteractor
import com.android.systemui.statusbar.notification.stack.domain.interactor.SharedNotificationContainerInteractor
import com.android.systemui.util.kotlin.Utils.Companion.sample as sampleCombine
@@ -67,7 +68,6 @@
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
-import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onStart
@@ -100,21 +100,35 @@
setOf(AOD, LOCKSCREEN, DOZING, ALTERNATE_BOUNCER, PRIMARY_BOUNCER)
private val edgeToAlphaViewModel =
- mapOf<Edge?, Flow<Float>>(
+ mapOf<Edge?, (ViewStateAccessor) -> Flow<Float>>(
Edge(from = LOCKSCREEN, to = DREAMING) to
- lockscreenToDreamingTransitionViewModel.lockscreenAlpha,
+ { _: ViewStateAccessor ->
+ lockscreenToDreamingTransitionViewModel.lockscreenAlpha
+ },
Edge(from = LOCKSCREEN, to = GONE) to
- lockscreenToGoneTransitionViewModel.lockscreenAlpha,
+ { viewState: ViewStateAccessor ->
+ lockscreenToGoneTransitionViewModel.lockscreenAlpha(viewState)
+ },
Edge(from = ALTERNATE_BOUNCER, to = GONE) to
- alternateBouncerToGoneTransitionViewModel.lockscreenAlpha,
+ { _: ViewStateAccessor ->
+ alternateBouncerToGoneTransitionViewModel.lockscreenAlpha
+ },
Edge(from = PRIMARY_BOUNCER, to = GONE) to
- primaryBouncerToGoneTransitionViewModel.lockscreenAlpha,
+ { _: ViewStateAccessor ->
+ primaryBouncerToGoneTransitionViewModel.lockscreenAlpha
+ },
Edge(from = DREAMING, to = LOCKSCREEN) to
- dreamingToLockscreenTransitionViewModel.lockscreenAlpha,
+ { _: ViewStateAccessor ->
+ dreamingToLockscreenTransitionViewModel.lockscreenAlpha
+ },
Edge(from = LOCKSCREEN, to = OCCLUDED) to
- lockscreenToOccludedTransitionViewModel.lockscreenAlpha,
+ { _: ViewStateAccessor ->
+ lockscreenToOccludedTransitionViewModel.lockscreenAlpha
+ },
Edge(from = OCCLUDED, to = LOCKSCREEN) to
- occludedToLockscreenTransitionViewModel.lockscreenAlpha,
+ { _: ViewStateAccessor ->
+ occludedToLockscreenTransitionViewModel.lockscreenAlpha
+ },
)
private val lockscreenTransitionInProgress: Flow<Edge?> =
@@ -151,21 +165,20 @@
val configurationBasedDimensions: Flow<ConfigurationBasedDimensions> =
interactor.configurationBasedDimensions
.map {
+ val marginTop =
+ if (it.useLargeScreenHeader) it.marginTopLargeScreen else it.marginTop
ConfigurationBasedDimensions(
marginStart = if (it.useSplitShade) 0 else it.marginHorizontal,
marginEnd = it.marginHorizontal,
marginBottom = it.marginBottom,
- marginTop =
- if (it.useLargeScreenHeader) it.marginTopLargeScreen else it.marginTop,
+ marginTop = marginTop,
useSplitShade = it.useSplitShade,
paddingTop =
if (it.useSplitShade) {
- // When in split shade, the margin is applied twice as the legacy shade
- // code uses it to calculate padding.
- it.keyguardSplitShadeTopMargin - 2 * it.marginTopLargeScreen
+ marginTop
} else {
0
- }
+ },
)
}
.distinctUntilChanged()
@@ -255,13 +268,15 @@
isOnLockscreenWithoutShade,
keyguardInteractor.notificationContainerBounds,
configurationBasedDimensions,
- interactor.topPosition.sampleCombine(
- keyguardTransitionInteractor.isInTransitionToAnyState,
- shadeInteractor.qsExpansion,
- ),
+ interactor.topPosition
+ .sampleCombine(
+ keyguardTransitionInteractor.isInTransitionToAnyState,
+ shadeInteractor.qsExpansion,
+ )
+ .onStart { emit(Triple(0f, false, 0f)) }
) { onLockscreen, bounds, config, (top, isInTransitionToAnyState, qsExpansion) ->
if (onLockscreen) {
- bounds.copy(top = bounds.top + config.paddingTop)
+ bounds.copy(top = bounds.top - config.paddingTop)
} else {
// When QS expansion > 0, it should directly set the top padding so do not
// animate it
@@ -278,46 +293,63 @@
initialValue = NotificationContainerBounds(),
)
- /** As QS is expanding, fade out notifications unless in splitshade */
- private val alphaForQsExpansion: Flow<Float> =
- interactor.configurationBasedDimensions.flatMapLatest {
- if (it.useSplitShade) {
- flowOf(1f)
- } else {
- shadeInteractor.qsExpansion.map { 1f - it }
+ /**
+ * Ensure view is visible when the shade/qs are expanded. Also, as QS is expanding, fade out
+ * notifications unless in splitshade.
+ */
+ private val alphaForShadeAndQsExpansion: Flow<Float> =
+ interactor.configurationBasedDimensions
+ .flatMapLatest { configurationBasedDimensions ->
+ combine(
+ shadeInteractor.shadeExpansion,
+ shadeInteractor.qsExpansion,
+ ) { shadeExpansion, qsExpansion ->
+ if (shadeExpansion > 0f || qsExpansion > 0f) {
+ if (configurationBasedDimensions.useSplitShade) {
+ 1f
+ } else {
+ // Fade as QS shade expands
+ 1f - qsExpansion
+ }
+ } else {
+ // Not visible unless the shade/qs is visible
+ 0f
+ }
+ }
}
- }
+ .distinctUntilChanged()
- val expansionAlpha: Flow<Float> =
+ fun expansionAlpha(viewState: ViewStateAccessor): Flow<Float> {
// Due to issues with the legacy shade, some shade expansion events are sent incorrectly,
// such as when the shade resets. This can happen while the transition to/from LOCKSCREEN
// is running. Therefore use a series of flatmaps to prevent unwanted interruptions while
// those transitions are in progress. Without this, the alpha value will produce a visible
// flicker.
- lockscreenTransitionInProgress
+ return lockscreenTransitionInProgress
.flatMapLatest { edge ->
- edgeToAlphaViewModel.getOrElse(
+ edgeToAlphaViewModel.getOrDefault(
edge,
- {
+ { _: ViewStateAccessor ->
isOnLockscreenWithoutShade.flatMapLatest { isOnLockscreenWithoutShade ->
combineTransform(
keyguardInteractor.keyguardAlpha,
shadeCollpaseFadeIn,
- alphaForQsExpansion,
- ) { alpha, shadeCollpaseFadeIn, alphaForQsExpansion ->
+ alphaForShadeAndQsExpansion,
+ ) { alpha, shadeCollpaseFadeIn, alphaForShadeAndQsExpansion ->
if (isOnLockscreenWithoutShade) {
if (!shadeCollpaseFadeIn) {
emit(alpha)
}
} else {
- emit(alphaForQsExpansion)
+ emit(alphaForShadeAndQsExpansion)
}
}
}
}
- )
+ )(viewState)
}
.distinctUntilChanged()
+ }
/**
* Returns a flow of the expected alpha while running a LOCKSCREEN<->GLANCEABLE_HUB transition
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java
index ca3e3c6..db55da7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithm.java
@@ -43,6 +43,7 @@
*/
public class KeyguardClockPositionAlgorithm {
private static final String TAG = "KeyguardClockPositionAlgorithm";
+ private static final boolean DEBUG = false;
/**
* Margin between the bottom of the status view and the notification shade.
@@ -318,24 +319,26 @@
}
float fullyDarkBurnInOffset = burnInPreventionOffsetY(burnInPreventionOffsetY);
- float clockYDark = clockY
- + fullyDarkBurnInOffset
- + shift;
+ float clockYDark = clockY + fullyDarkBurnInOffset + shift;
mCurrentBurnInOffsetY = MathUtils.lerp(0, fullyDarkBurnInOffset, darkAmount);
- final String inputs = "panelExpansion: " + panelExpansion + " darkAmount: " + darkAmount;
- final String outputs = "clockY: " + clockY
- + " burnInPreventionOffsetY: " + burnInPreventionOffsetY
- + " fullyDarkBurnInOffset: " + fullyDarkBurnInOffset
- + " shift: " + shift
- + " mOverStretchAmount: " + mOverStretchAmount
- + " mCurrentBurnInOffsetY: " + mCurrentBurnInOffsetY;
- mLogger.i(msg -> {
- return msg.getStr1() + " -> " + msg.getStr2();
- }, msg -> {
- msg.setStr1(inputs);
- msg.setStr2(outputs);
- return kotlin.Unit.INSTANCE;
- });
+
+ if (DEBUG) {
+ final float finalShift = shift;
+ final float finalBurnInPreventionOffsetY = burnInPreventionOffsetY;
+ mLogger.i(msg -> {
+ final String inputs = "panelExpansion: " + panelExpansion
+ + " darkAmount: " + darkAmount;
+ final String outputs = "clockY: " + clockY
+ + " burnInPreventionOffsetY: " + finalBurnInPreventionOffsetY
+ + " fullyDarkBurnInOffset: " + fullyDarkBurnInOffset
+ + " shift: " + finalShift
+ + " mOverStretchAmount: " + mOverStretchAmount
+ + " mCurrentBurnInOffsetY: " + mCurrentBurnInOffsetY;
+ return inputs + " -> " + outputs;
+ }, msg -> {
+ return kotlin.Unit.INSTANCE;
+ });
+ }
return (int) (MathUtils.lerp(clockY, clockYDark, darkAmount) + mOverStretchAmount);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
index 45bdae8..8ac3b4a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
@@ -132,9 +132,9 @@
if (updateDisplayParameters()) {
updateLayoutForCutout();
requestLayout();
- if (truncatedStatusBarIconsFix()) {
- updateWindowHeight();
- }
+ }
+ if (truncatedStatusBarIconsFix()) {
+ updateWindowHeight();
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyController.java
index fb67358..eb08f37 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyController.java
@@ -16,12 +16,9 @@
package com.android.systemui.statusbar.policy;
-import android.annotation.FlaggedApi;
import android.hardware.SensorPrivacyManager.Sensors.Sensor;
import android.hardware.SensorPrivacyManager.Sources.Source;
-import com.android.internal.camera.flags.Flags;
-
public interface IndividualSensorPrivacyController extends
CallbackController<IndividualSensorPrivacyController.Callback> {
void init();
@@ -45,12 +42,6 @@
*/
boolean requiresAuthentication();
- /**
- * @return whether camera privacy is enabled for the package.
- */
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- boolean isCameraPrivacyEnabled(String packageName);
-
interface Callback {
void onSensorBlockedChanged(@Sensor int sensor, boolean blocked);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyControllerImpl.java
index 8f768e9..87dfc99 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/IndividualSensorPrivacyControllerImpl.java
@@ -19,9 +19,6 @@
import static android.hardware.SensorPrivacyManager.Sensors.CAMERA;
import static android.hardware.SensorPrivacyManager.Sensors.MICROPHONE;
-import android.Manifest;
-import android.annotation.FlaggedApi;
-import android.annotation.RequiresPermission;
import android.hardware.SensorPrivacyManager;
import android.hardware.SensorPrivacyManager.Sensors.Sensor;
import android.hardware.SensorPrivacyManager.Sources.Source;
@@ -31,8 +28,6 @@
import androidx.annotation.NonNull;
-import com.android.internal.camera.flags.Flags;
-
import java.util.Set;
public class IndividualSensorPrivacyControllerImpl implements IndividualSensorPrivacyController {
@@ -107,13 +102,6 @@
}
@Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
- public boolean isCameraPrivacyEnabled(String packageName) {
- return mSensorPrivacyManager.isCameraPrivacyEnabled(packageName);
- }
-
- @Override
public void addCallback(@NonNull Callback listener) {
mCallbacks.add(listener);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java
index 9f4a906..f397627 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java
@@ -444,7 +444,8 @@
UserHandle.of(userId))) {
boolean hasCACerts = !(conn.getService().getUserCaAliases().getList().isEmpty());
idWithCert = new Pair<Integer, Boolean>(userId, hasCACerts);
- } catch (RemoteException | InterruptedException | AssertionError e) {
+ } catch (RemoteException | InterruptedException | AssertionError
+ | IllegalStateException e) {
Log.i(TAG, "failed to get CA certs", e);
idWithCert = new Pair<Integer, Boolean>(userId, null);
} finally {
diff --git a/packages/SystemUI/tests/src/android/animation/AnimatorTestRuleIsolationTest.kt b/packages/SystemUI/tests/src/android/animation/AnimatorTestRuleIsolationTest.kt
index 0fe2283..f23fbee 100644
--- a/packages/SystemUI/tests/src/android/animation/AnimatorTestRuleIsolationTest.kt
+++ b/packages/SystemUI/tests/src/android/animation/AnimatorTestRuleIsolationTest.kt
@@ -34,7 +34,7 @@
@RunWithLooper
class AnimatorTestRuleIsolationTest : SysuiTestCase() {
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
@Test
fun testA() {
diff --git a/packages/SystemUI/tests/src/android/animation/AnimatorTestRulePrecisionTest.kt b/packages/SystemUI/tests/src/android/animation/AnimatorTestRulePrecisionTest.kt
index cc7f7e4..fd5f157 100644
--- a/packages/SystemUI/tests/src/android/animation/AnimatorTestRulePrecisionTest.kt
+++ b/packages/SystemUI/tests/src/android/animation/AnimatorTestRulePrecisionTest.kt
@@ -31,7 +31,7 @@
@RunWithLooper
class AnimatorTestRulePrecisionTest : SysuiTestCase() {
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
var value1: Float = -1f
var value2: Float = -1f
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
index e6637e6..cd19259 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
@@ -22,6 +22,7 @@
import android.widget.FrameLayout
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.Flags as AConfigFlags
import com.android.systemui.broadcast.BroadcastDispatcher
import com.android.systemui.flags.Flags
import com.android.systemui.keyguard.data.repository.FakeKeyguardRepository
@@ -259,6 +260,7 @@
@Test
fun keyguardCallback_visibilityChanged_clockDozeCalled() =
runBlocking(IMMEDIATE) {
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
val captor = argumentCaptor<KeyguardUpdateMonitorCallback>()
verify(keyguardUpdateMonitor).registerCallback(capture(captor))
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java
index fad8552..e893eb1 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardStatusViewControllerTest.java
@@ -56,7 +56,7 @@
public class KeyguardStatusViewControllerTest extends KeyguardStatusViewControllerBaseTest {
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(this);
@Test
public void dozeTimeTick_updatesSlice() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java
index ba27fcd..dd428f5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ExpandHelperTest.java
@@ -48,7 +48,7 @@
public class ExpandHelperTest extends SysuiTestCase {
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(this);
private final FakeFeatureFlags mFeatureFlags = new FakeFeatureFlags();
private ExpandableNotificationRow mRow;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java
index e006d59..64936862 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java
@@ -82,7 +82,7 @@
public class WindowMagnificationAnimationControllerTest extends SysuiTestCase {
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(this);
@Rule
public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
private static final float DEFAULT_SCALE = 4.0f;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java
index 2225ad6..f1b0c18 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerTest.java
@@ -129,7 +129,8 @@
public class WindowMagnificationControllerTest extends SysuiTestCase {
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ // NOTE: pass 'null' to allow this test advances time on the main thread.
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(null);
@Rule
public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerWindowlessMagnifierTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerWindowlessMagnifierTest.java
index a35a509..08b49e7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerWindowlessMagnifierTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationControllerWindowlessMagnifierTest.java
@@ -132,7 +132,7 @@
public class WindowMagnificationControllerWindowlessMagnifierTest extends SysuiTestCase {
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(this);
@Rule
public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt
index 2b51ac5..e3be3822 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt
@@ -34,7 +34,7 @@
@FlakyTest(bugId = 302149604)
class AnimatorTestRuleOrderTest : SysuiTestCase() {
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
var value1: Float = -1f
var value2: Float = -1f
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequestTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequestTest.kt
index a46167a42..8fab233 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequestTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/domain/model/BiometricPromptRequestTest.kt
@@ -26,6 +26,7 @@
@Test
fun biometricRequestFromPromptInfo() {
val logoRes = R.drawable.ic_cake
+ val logoDescription = "test cake"
val title = "what"
val subtitle = "a"
val description = "request"
@@ -41,6 +42,7 @@
BiometricPromptRequest.Biometric(
promptInfo(
logoRes = logoRes,
+ logoDescription = logoDescription,
title = title,
subtitle = subtitle,
description = description,
@@ -53,6 +55,7 @@
)
assertThat(request.logoRes).isEqualTo(logoRes)
+ assertThat(request.logoDescription).isEqualTo(logoDescription)
assertThat(request.title).isEqualTo(title)
assertThat(request.subtitle).isEqualTo(subtitle)
assertThat(request.description).isEqualTo(description)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
index 2e94d38..ff68fe3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
@@ -16,6 +16,7 @@
package com.android.systemui.biometrics.ui.viewmodel
+import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Bitmap
@@ -74,6 +75,8 @@
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.junit.MockitoJUnit
@@ -95,6 +98,8 @@
@Mock private lateinit var selectedUserInteractor: SelectedUserInteractor
@Mock private lateinit var udfpsUtils: UdfpsUtils
@Mock private lateinit var packageManager: PackageManager
+ @Mock private lateinit var applicationInfoWithIcon: ApplicationInfo
+ @Mock private lateinit var applicationInfoNoIcon: ApplicationInfo
private val fakeExecutor = FakeExecutor(FakeSystemClock())
private val testScope = TestScope()
@@ -102,6 +107,8 @@
private val logoResFromApp = R.drawable.ic_cake
private val logoFromApp = context.getDrawable(logoResFromApp)
private val logoBitmapFromApp = Bitmap.createBitmap(400, 400, Bitmap.Config.RGB_565)
+ private val defaultLogoDescription = "Test Android App"
+ private val logoDescriptionFromApp = "Test Cake App"
private lateinit var fingerprintRepository: FakeFingerprintPropertyRepository
private lateinit var promptRepository: FakePromptRepository
@@ -166,7 +173,14 @@
iconViewModel = viewModel.iconViewModel
// Set up default logo icon and app customized icon
- whenever(packageManager.getApplicationIcon(OP_PACKAGE_NAME)).thenReturn(defaultLogoIcon)
+ whenever(packageManager.getApplicationInfo(eq(OP_PACKAGE_NAME_NO_ICON), anyInt()))
+ .thenReturn(applicationInfoNoIcon)
+ whenever(packageManager.getApplicationInfo(eq(OP_PACKAGE_NAME), anyInt()))
+ .thenReturn(applicationInfoWithIcon)
+ whenever(packageManager.getApplicationIcon(applicationInfoWithIcon))
+ .thenReturn(defaultLogoIcon)
+ whenever(packageManager.getApplicationLabel(applicationInfoWithIcon))
+ .thenReturn(defaultLogoDescription)
context.setMockPackageManager(packageManager)
val resources = context.getOrCreateTestableResources()
resources.addOverride(logoResFromApp, logoFromApp)
@@ -1277,6 +1291,29 @@
assertThat((logo as BitmapDrawable).bitmap).isEqualTo(logoBitmapFromApp)
}
+ @Test
+ fun logoDescriptionIsEmptyIfPackageNameNotFound() =
+ runGenericTest(packageName = OP_PACKAGE_NAME_NO_ICON) {
+ mSetFlagsRule.enableFlags(FLAG_CUSTOM_BIOMETRIC_PROMPT)
+ val logoDescription by collectLastValue(viewModel.logoDescription)
+ assertThat(logoDescription).isEqualTo("")
+ }
+
+ @Test
+ fun defaultLogoDescriptionIfNoLogoDescriptionSet() = runGenericTest {
+ mSetFlagsRule.enableFlags(FLAG_CUSTOM_BIOMETRIC_PROMPT)
+ val logoDescription by collectLastValue(viewModel.logoDescription)
+ assertThat(logoDescription).isEqualTo(defaultLogoDescription)
+ }
+
+ @Test
+ fun logoDescriptionSetByApp() =
+ runGenericTest(logoDescription = logoDescriptionFromApp) {
+ mSetFlagsRule.enableFlags(FLAG_CUSTOM_BIOMETRIC_PROMPT)
+ val logoDescription by collectLastValue(viewModel.logoDescription)
+ assertThat(logoDescription).isEqualTo(logoDescriptionFromApp)
+ }
+
/** Asserts that the selected buttons are visible now. */
private suspend fun TestScope.assertButtonsVisible(
tryAgain: Boolean = false,
@@ -1300,6 +1337,7 @@
contentView: PromptContentView? = null,
logoRes: Int = -1,
logoBitmap: Bitmap? = null,
+ logoDescription: String? = null,
packageName: String = OP_PACKAGE_NAME,
block: suspend TestScope.() -> Unit,
) {
@@ -1312,6 +1350,7 @@
contentViewFromApp = contentView,
logoResFromApp = logoRes,
logoBitmapFromApp = logoBitmap,
+ logoDescriptionFromApp = logoDescription,
packageName = packageName,
)
@@ -1492,12 +1531,14 @@
contentViewFromApp: PromptContentView? = null,
logoResFromApp: Int = -1,
logoBitmapFromApp: Bitmap? = null,
+ logoDescriptionFromApp: String? = null,
packageName: String = OP_PACKAGE_NAME,
) {
val info =
PromptInfo().apply {
logoRes = logoResFromApp
logoBitmap = logoBitmapFromApp
+ logoDescription = logoDescriptionFromApp
title = "t"
subtitle = "s"
description = descriptionFromApp
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplierTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplierTest.kt
index 5b29a86..7787a7f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplierTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/binder/KeyguardSurfaceBehindParamsApplierTest.kt
@@ -43,7 +43,7 @@
@RunWithLooper(setAsMainLooper = true)
@kotlinx.coroutines.ExperimentalCoroutinesApi
class KeyguardSurfaceBehindParamsApplierTest : SysuiTestCase() {
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
private lateinit var underTest: KeyguardSurfaceBehindParamsApplier
private lateinit var executor: FakeExecutor
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt
index 8b05a54..e7aaddd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/LockscreenToGoneTransitionViewModelTest.kt
@@ -19,6 +19,7 @@
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
import com.android.systemui.coroutines.collectValues
import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
import com.android.systemui.keyguard.shared.model.KeyguardState
@@ -56,6 +57,41 @@
deviceEntryParentViewAlpha.forEach { assertThat(it).isEqualTo(0f) }
}
+ @Test
+ fun lockscreenAlphaStartsFromViewStateAccessorAlpha() =
+ testScope.runTest {
+ val viewState = ViewStateAccessor(alpha = { 0.5f })
+ val alpha by collectLastValue(underTest.lockscreenAlpha(viewState))
+
+ repository.sendTransitionStep(step(0f, TransitionState.STARTED))
+
+ repository.sendTransitionStep(step(0f))
+ assertThat(alpha).isEqualTo(0.5f)
+
+ repository.sendTransitionStep(step(0.25f))
+ assertThat(alpha).isEqualTo(0.25f)
+
+ repository.sendTransitionStep(step(.5f))
+ assertThat(alpha).isEqualTo(0f)
+ }
+
+ @Test
+ fun lockscreenAlphaWithNoViewStateAccessorValue() =
+ testScope.runTest {
+ val alpha by collectLastValue(underTest.lockscreenAlpha(ViewStateAccessor()))
+
+ repository.sendTransitionStep(step(0f, TransitionState.STARTED))
+
+ repository.sendTransitionStep(step(0f))
+ assertThat(alpha).isEqualTo(0f)
+
+ repository.sendTransitionStep(step(0.25f))
+ assertThat(alpha).isEqualTo(0f)
+
+ repository.sendTransitionStep(step(0.5f))
+ assertThat(alpha).isEqualTo(0f)
+ }
+
private fun step(
value: Float,
state: TransitionState = TransitionState.RUNNING
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/controls/models/player/SeekBarObserverTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/controls/models/player/SeekBarObserverTest.kt
index 100e579..4ec29ce 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/controls/models/player/SeekBarObserverTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/controls/models/player/SeekBarObserverTest.kt
@@ -164,6 +164,18 @@
}
@Test
+ fun seekbarNotListeningNotScrubbingPlaying() {
+ // WHEN playing
+ val isPlaying = true
+ val isScrubbing = false
+ val data =
+ SeekBarViewModel.Progress(true, true, isPlaying, isScrubbing, 3000, 120000, false)
+ observer.onChanged(data)
+ // THEN progress drawable is not animating
+ verify(mockSquigglyProgress).animate = false
+ }
+
+ @Test
fun seekBarPlayingScrubbing() {
// WHEN playing & scrubbing
val isPlaying = true
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest_311121830.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest_311121830.kt
index bbae0c9..ae2a9ad 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest_311121830.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSIconViewImplTest_311121830.kt
@@ -40,7 +40,7 @@
@SmallTest
class QSIconViewImplTest_311121830 : SysuiTestCase() {
- @get:Rule val animatorRule = AnimatorTestRule()
+ @get:Rule val animatorRule = AnimatorTestRule(this)
@Test
fun alwaysLastIcon() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnInteractorTest.kt
new file mode 100644
index 0000000..3710713
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnInteractorTest.kt
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.dialog.bluetooth
+
+import android.content.pm.UserInfo
+import android.testing.AndroidTestingRunner
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.user.data.repository.FakeUserRepository
+import com.android.systemui.util.settings.FakeSettings
+import com.google.common.truth.Truth
+import kotlin.test.Test
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Rule
+import org.junit.runner.RunWith
+import org.mockito.junit.MockitoJUnit
+import org.mockito.junit.MockitoRule
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+class BluetoothAutoOnInteractorTest : SysuiTestCase() {
+ @get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule()
+ private val testDispatcher = StandardTestDispatcher()
+ private val testScope = TestScope(testDispatcher)
+ private var secureSettings: FakeSettings = FakeSettings()
+ private val userRepository: FakeUserRepository = FakeUserRepository()
+ private lateinit var bluetoothAutoOnInteractor: BluetoothAutoOnInteractor
+
+ @Before
+ fun setUp() {
+ bluetoothAutoOnInteractor =
+ BluetoothAutoOnInteractor(
+ BluetoothAutoOnRepository(
+ secureSettings,
+ userRepository,
+ testScope.backgroundScope,
+ testDispatcher
+ )
+ )
+ }
+
+ @Test
+ fun testSet_bluetoothAutoOnUnset_doNothing() {
+ testScope.runTest {
+ bluetoothAutoOnInteractor.setEnabled(true)
+
+ val actualValue by collectLastValue(bluetoothAutoOnInteractor.isEnabled)
+
+ runCurrent()
+
+ Truth.assertThat(actualValue).isEqualTo(false)
+ }
+ }
+
+ @Test
+ fun testSet_bluetoothAutoOnSet_setNewValue() {
+ testScope.runTest {
+ userRepository.setUserInfos(listOf(SYSTEM_USER))
+ secureSettings.putIntForUser(
+ BluetoothAutoOnRepository.SETTING_NAME,
+ BluetoothAutoOnInteractor.DISABLED,
+ SYSTEM_USER_ID
+ )
+ bluetoothAutoOnInteractor.setEnabled(true)
+
+ val actualValue by collectLastValue(bluetoothAutoOnInteractor.isEnabled)
+
+ runCurrent()
+
+ Truth.assertThat(actualValue).isEqualTo(true)
+ }
+ }
+
+ companion object {
+ private const val SYSTEM_USER_ID = 0
+ private val SYSTEM_USER =
+ UserInfo(/* id= */ SYSTEM_USER_ID, /* name= */ "system user", /* flags= */ 0)
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnRepositoryTest.kt
new file mode 100644
index 0000000..8986d99
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothAutoOnRepositoryTest.kt
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.dialog.bluetooth
+
+import android.content.pm.UserInfo
+import android.os.UserHandle
+import android.testing.AndroidTestingRunner
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothAutoOnInteractor.Companion.DISABLED
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothAutoOnInteractor.Companion.ENABLED
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothAutoOnRepository.Companion.SETTING_NAME
+import com.android.systemui.qs.tiles.dialog.bluetooth.BluetoothAutoOnRepository.Companion.UNSET
+import com.android.systemui.user.data.repository.FakeUserRepository
+import com.android.systemui.util.settings.FakeSettings
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.junit.MockitoJUnit
+import org.mockito.junit.MockitoRule
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+class BluetoothAutoOnRepositoryTest : SysuiTestCase() {
+ @get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule()
+ private val testDispatcher = StandardTestDispatcher()
+ private val testScope = TestScope(testDispatcher)
+ private var secureSettings: FakeSettings = FakeSettings()
+ private val userRepository: FakeUserRepository = FakeUserRepository()
+
+ private lateinit var bluetoothAutoOnRepository: BluetoothAutoOnRepository
+
+ @Before
+ fun setUp() {
+ bluetoothAutoOnRepository =
+ BluetoothAutoOnRepository(
+ secureSettings,
+ userRepository,
+ testScope.backgroundScope,
+ testDispatcher
+ )
+
+ userRepository.setUserInfos(listOf(SECONDARY_USER, SYSTEM_USER))
+ }
+
+ @Test
+ fun testGetValue_valueUnset() {
+ testScope.runTest {
+ userRepository.setSelectedUserInfo(SYSTEM_USER)
+ val actualValue by collectLastValue(bluetoothAutoOnRepository.getValue)
+
+ runCurrent()
+
+ assertThat(actualValue).isEqualTo(UNSET)
+ assertThat(bluetoothAutoOnRepository.isValuePresent()).isFalse()
+ }
+ }
+
+ @Test
+ fun testGetValue_valueFalse() {
+ testScope.runTest {
+ userRepository.setSelectedUserInfo(SYSTEM_USER)
+ val actualValue by collectLastValue(bluetoothAutoOnRepository.getValue)
+
+ secureSettings.putIntForUser(SETTING_NAME, DISABLED, UserHandle.USER_SYSTEM)
+ runCurrent()
+
+ assertThat(actualValue).isEqualTo(DISABLED)
+ }
+ }
+
+ @Test
+ fun testGetValue_valueTrue() {
+ testScope.runTest {
+ userRepository.setSelectedUserInfo(SYSTEM_USER)
+ val actualValue by collectLastValue(bluetoothAutoOnRepository.getValue)
+
+ secureSettings.putIntForUser(SETTING_NAME, ENABLED, UserHandle.USER_SYSTEM)
+ runCurrent()
+
+ assertThat(actualValue).isEqualTo(ENABLED)
+ }
+ }
+
+ @Test
+ fun testGetValue_valueTrue_secondaryUser_returnUnset() {
+ testScope.runTest {
+ userRepository.setSelectedUserInfo(SECONDARY_USER)
+ val actualValue by collectLastValue(bluetoothAutoOnRepository.getValue)
+
+ secureSettings.putIntForUser(SETTING_NAME, ENABLED, SECONDARY_USER_ID)
+ runCurrent()
+
+ assertThat(actualValue).isEqualTo(UNSET)
+ }
+ }
+
+ companion object {
+ private const val SYSTEM_USER_ID = 0
+ private const val SECONDARY_USER_ID = 1
+ private val SYSTEM_USER =
+ UserInfo(/* id= */ SYSTEM_USER_ID, /* name= */ "system user", /* flags= */ 0)
+ private val SECONDARY_USER =
+ UserInfo(/* id= */ SECONDARY_USER_ID, /* name= */ "secondary user", /* flags= */ 0)
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogTest.kt
index 154aa1c..70b0417 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogTest.kt
@@ -71,7 +71,11 @@
@Mock private lateinit var logger: BluetoothTileDialogLogger
- private val subtitleResId = R.string.quick_settings_bluetooth_tile_subtitle
+ private val uiProperties =
+ BluetoothTileDialogViewModel.UiProperties.build(
+ isBluetoothEnabled = ENABLED,
+ isAutoOnToggleFeatureAvailable = ENABLED
+ )
private val fakeSystemClock = FakeSystemClock()
@@ -90,7 +94,7 @@
bluetoothTileDialog =
BluetoothTileDialog(
ENABLED,
- subtitleResId,
+ uiProperties,
CONTENT_HEIGHT,
bluetoothTileDialogCallback,
dispatcher,
@@ -131,7 +135,7 @@
bluetoothTileDialog =
BluetoothTileDialog(
ENABLED,
- subtitleResId,
+ uiProperties,
CONTENT_HEIGHT,
bluetoothTileDialogCallback,
dispatcher,
@@ -166,7 +170,7 @@
val viewHolder =
BluetoothTileDialog(
ENABLED,
- subtitleResId,
+ uiProperties,
CONTENT_HEIGHT,
bluetoothTileDialogCallback,
dispatcher,
@@ -194,7 +198,7 @@
val viewHolder =
BluetoothTileDialog(
ENABLED,
- subtitleResId,
+ uiProperties,
CONTENT_HEIGHT,
bluetoothTileDialogCallback,
dispatcher,
@@ -219,7 +223,7 @@
bluetoothTileDialog =
BluetoothTileDialog(
ENABLED,
- subtitleResId,
+ uiProperties,
CONTENT_HEIGHT,
bluetoothTileDialogCallback,
dispatcher,
@@ -253,12 +257,36 @@
}
@Test
- fun testShowDialog_displayFromCachedHeight() {
+ fun testShowDialog_cachedHeightLargerThanMinHeight_displayFromCachedHeight() {
+ testScope.runTest {
+ val cachedHeight = Int.MAX_VALUE
+ bluetoothTileDialog =
+ BluetoothTileDialog(
+ ENABLED,
+ uiProperties,
+ cachedHeight,
+ bluetoothTileDialogCallback,
+ dispatcher,
+ fakeSystemClock,
+ uiEventLogger,
+ logger,
+ mContext
+ )
+ bluetoothTileDialog.show()
+ assertThat(
+ bluetoothTileDialog.requireViewById<View>(R.id.scroll_view).layoutParams.height
+ )
+ .isEqualTo(cachedHeight)
+ }
+ }
+
+ @Test
+ fun testShowDialog_cachedHeightLessThanMinHeight_displayFromUiProperties() {
testScope.runTest {
bluetoothTileDialog =
BluetoothTileDialog(
ENABLED,
- subtitleResId,
+ uiProperties,
MATCH_PARENT,
bluetoothTileDialogCallback,
dispatcher,
@@ -271,7 +299,32 @@
assertThat(
bluetoothTileDialog.requireViewById<View>(R.id.scroll_view).layoutParams.height
)
- .isEqualTo(MATCH_PARENT)
+ .isGreaterThan(MATCH_PARENT)
+ }
+ }
+
+ @Test
+ fun testShowDialog_bluetoothEnabled_autoOnToggleGone() {
+ testScope.runTest {
+ bluetoothTileDialog =
+ BluetoothTileDialog(
+ ENABLED,
+ BluetoothTileDialogViewModel.UiProperties.build(ENABLED, ENABLED),
+ MATCH_PARENT,
+ bluetoothTileDialogCallback,
+ dispatcher,
+ fakeSystemClock,
+ uiEventLogger,
+ logger,
+ mContext
+ )
+ bluetoothTileDialog.show()
+ assertThat(
+ bluetoothTileDialog
+ .requireViewById<View>(R.id.bluetooth_auto_on_toggle_layout)
+ .visibility
+ )
+ .isEqualTo(GONE)
}
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt
index 98ac17b..cb9f4b4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/BluetoothTileDialogViewModelTest.kt
@@ -17,20 +17,27 @@
package com.android.systemui.qs.tiles.dialog.bluetooth
import android.content.SharedPreferences
+import android.content.pm.UserInfo
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper
import android.view.View
+import android.view.View.GONE
+import android.view.View.VISIBLE
import android.widget.LinearLayout
import androidx.test.filters.SmallTest
import com.android.internal.logging.UiEventLogger
import com.android.settingslib.bluetooth.CachedBluetoothDevice
+import com.android.settingslib.flags.Flags
import com.android.systemui.SysuiTestCase
import com.android.systemui.animation.DialogTransitionAnimator
import com.android.systemui.plugins.ActivityStarter
+import com.android.systemui.user.data.repository.FakeUserRepository
import com.android.systemui.util.concurrency.FakeExecutor
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.nullable
+import com.android.systemui.util.settings.FakeSettings
import com.android.systemui.util.time.FakeSystemClock
+import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
@@ -84,16 +91,36 @@
private lateinit var scheduler: TestCoroutineScheduler
private lateinit var dispatcher: CoroutineDispatcher
private lateinit var testScope: TestScope
+ private lateinit var secureSettings: FakeSettings
+ private lateinit var userRepository: FakeUserRepository
@Before
fun setUp() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_BLUETOOTH_QS_TILE_DIALOG_AUTO_ON_TOGGLE)
scheduler = TestCoroutineScheduler()
dispatcher = UnconfinedTestDispatcher(scheduler)
testScope = TestScope(dispatcher)
+ secureSettings = FakeSettings()
+ userRepository = FakeUserRepository()
+ userRepository.setUserInfos(listOf(SYSTEM_USER))
+ secureSettings.putIntForUser(
+ BluetoothAutoOnRepository.SETTING_NAME,
+ BluetoothAutoOnInteractor.ENABLED,
+ SYSTEM_USER_ID
+ )
bluetoothTileDialogViewModel =
BluetoothTileDialogViewModel(
deviceItemInteractor,
bluetoothStateInteractor,
+ // TODO(b/316822488): Create FakeBluetoothAutoOnInteractor.
+ BluetoothAutoOnInteractor(
+ BluetoothAutoOnRepository(
+ secureSettings,
+ userRepository,
+ testScope.backgroundScope,
+ dispatcher
+ )
+ ),
mDialogTransitionAnimator,
activityStarter,
fakeSystemClock,
@@ -174,4 +201,64 @@
verify(activityStarter).postStartActivityDismissingKeyguard(any(), anyInt(), nullable())
}
}
+
+ @Test
+ fun testBuildUiProperties_bluetoothOn_shouldHideAutoOn() {
+ testScope.runTest {
+ val actual =
+ BluetoothTileDialogViewModel.UiProperties.build(
+ isBluetoothEnabled = true,
+ isAutoOnToggleFeatureAvailable = true
+ )
+ assertThat(actual.autoOnToggleVisibility).isEqualTo(GONE)
+ }
+ }
+
+ @Test
+ fun testBuildUiProperties_bluetoothOff_shouldShowAutoOn() {
+ testScope.runTest {
+ val actual =
+ BluetoothTileDialogViewModel.UiProperties.build(
+ isBluetoothEnabled = false,
+ isAutoOnToggleFeatureAvailable = true
+ )
+ assertThat(actual.autoOnToggleVisibility).isEqualTo(VISIBLE)
+ }
+ }
+
+ @Test
+ fun testBuildUiProperties_bluetoothOff_autoOnFeatureUnavailable_shouldHideAutoOn() {
+ testScope.runTest {
+ val actual =
+ BluetoothTileDialogViewModel.UiProperties.build(
+ isBluetoothEnabled = false,
+ isAutoOnToggleFeatureAvailable = false
+ )
+ assertThat(actual.autoOnToggleVisibility).isEqualTo(GONE)
+ }
+ }
+
+ @Test
+ fun testIsAutoOnToggleFeatureAvailable_flagOn_settingValueSet_returnTrue() {
+ testScope.runTest {
+ val actual = bluetoothTileDialogViewModel.isAutoOnToggleFeatureAvailable()
+ assertThat(actual).isTrue()
+ }
+ }
+
+ @Test
+ fun testIsAutoOnToggleFeatureAvailable_flagOff_settingValueSet_returnFalse() {
+ testScope.runTest {
+ mSetFlagsRule.disableFlags(Flags.FLAG_BLUETOOTH_QS_TILE_DIALOG_AUTO_ON_TOGGLE)
+
+ val actual = bluetoothTileDialogViewModel.isAutoOnToggleFeatureAvailable()
+ assertThat(actual).isFalse()
+ }
+ }
+
+ companion object {
+ private const val SYSTEM_USER_ID = 0
+ private val SYSTEM_USER =
+ UserInfo(/* id= */ SYSTEM_USER_ID, /* name= */ "system user", /* flags= */ 0)
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
index 0c4bf81..ab5e51c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationShadeWindowViewTest.kt
@@ -207,6 +207,7 @@
@Test
fun testDragDownHelperCalledWhenDraggingDown() =
testScope.runTest {
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
whenever(dragDownHelper.isDraggingDown).thenReturn(true)
val now = SystemClock.elapsedRealtime()
val ev = MotionEvent.obtain(now, now, MotionEvent.ACTION_UP, 0f, 0f, 0 /* meta */)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt
index c226121..4cc1234 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationsQSContainerControllerLegacyTest.kt
@@ -26,6 +26,7 @@
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.test.filters.SmallTest
+import com.android.systemui.Flags as AConfigFlags
import com.android.systemui.Flags.FLAG_CENTRALIZED_STATUS_BAR_DIMENS_REFACTOR
import com.android.systemui.SysuiTestCase
import com.android.systemui.fragments.FragmentHostManager
@@ -400,6 +401,7 @@
@Test
fun testSplitShadeLayout_isAlignedToGuideline() {
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
enableSplitShade()
underTest.updateResources()
assertThat(getConstraintSetLayout(R.id.qs_frame).endToEnd).isEqualTo(R.id.qs_edge_guideline)
@@ -409,6 +411,7 @@
@Test
fun testSinglePaneLayout_childrenHaveEqualMargins() {
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
disableSplitShade()
underTest.updateResources()
val qsStartMargin = getConstraintSetLayout(R.id.qs_frame).startMargin
@@ -425,6 +428,7 @@
@Test
fun testSplitShadeLayout_childrenHaveInsideMarginsOfZero() {
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
enableSplitShade()
underTest.updateResources()
assertThat(getConstraintSetLayout(R.id.qs_frame).endMargin).isEqualTo(0)
@@ -443,6 +447,7 @@
@Test
fun testLargeScreenLayout_refactorFlagOff_qsAndNotifsTopMarginIsOfHeaderHeightResource() {
mSetFlagsRule.disableFlags(FLAG_CENTRALIZED_STATUS_BAR_DIMENS_REFACTOR)
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
setLargeScreen()
val largeScreenHeaderResourceHeight = 100
val largeScreenHeaderHelperHeight = 200
@@ -465,6 +470,7 @@
@Test
fun testLargeScreenLayout_refactorFlagOn_qsAndNotifsTopMarginIsOfHeaderHeightHelper() {
mSetFlagsRule.enableFlags(FLAG_CENTRALIZED_STATUS_BAR_DIMENS_REFACTOR)
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
setLargeScreen()
val largeScreenHeaderResourceHeight = 100
val largeScreenHeaderHelperHeight = 200
@@ -486,6 +492,7 @@
@Test
fun testSmallScreenLayout_qsAndNotifsTopMarginIsZero() {
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
setSmallScreen()
underTest.updateResources()
assertThat(getConstraintSetLayout(R.id.qs_frame).topMargin).isEqualTo(0)
@@ -506,6 +513,7 @@
@Test
fun testSinglePaneShadeLayout_isAlignedToParent() {
+ mSetFlagsRule.disableFlags(AConfigFlags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL)
disableSplitShade()
underTest.updateResources()
assertThat(getConstraintSetLayout(R.id.qs_frame).endToEnd)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemEventChipAnimationControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemEventChipAnimationControllerTest.kt
index 8be2ef0..452302d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemEventChipAnimationControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemEventChipAnimationControllerTest.kt
@@ -51,7 +51,7 @@
class SystemEventChipAnimationControllerTest : SysuiTestCase() {
private lateinit var controller: SystemEventChipAnimationController
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
@Mock private lateinit var sbWindowController: StatusBarWindowController
@Mock private lateinit var insetsProvider: StatusBarContentInsetsProvider
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt
index 875fe58..cacfa8d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/events/SystemStatusAnimationSchedulerImplTest.kt
@@ -76,7 +76,7 @@
private lateinit var chipAnimationController: SystemEventChipAnimationController
private lateinit var systemStatusAnimationScheduler: SystemStatusAnimationScheduler
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
@Before
fun setup() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt
index 039fef9..82093ad 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinatorTest.kt
@@ -54,7 +54,7 @@
@TestableLooper.RunWithLooper(setAsMainLooper = true)
class NotificationWakeUpCoordinatorTest : SysuiTestCase() {
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
private val kosmos = Kosmos()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinatorTest.kt
index 7073cc7..85b8b03 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RemoteInputCoordinatorTest.kt
@@ -15,7 +15,13 @@
*/
package com.android.systemui.statusbar.notification.collection.coordinator
+import android.app.Flags.lifetimeExtensionRefactor
+import android.app.Flags.FLAG_LIFETIME_EXTENSION_REFACTOR
+import android.app.Notification
+import android.app.RemoteInputHistoryItem
import android.os.Handler
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
import android.service.notification.StatusBarNotification
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper.RunWithLooper
@@ -34,6 +40,7 @@
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifLifetimeExtender
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifLifetimeExtender.OnEndLifetimeExtensionCallback
import com.android.systemui.util.mockito.any
+import com.android.systemui.util.mockito.captureMany
import com.android.systemui.util.mockito.withArgCaptor
import com.google.common.truth.Truth.assertThat
import org.junit.Before
@@ -42,6 +49,7 @@
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.never
+import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations.initMocks
@@ -57,6 +65,7 @@
private lateinit var entry2: NotificationEntry
@Mock private lateinit var lifetimeExtensionCallback: OnEndLifetimeExtensionCallback
+
@Mock private lateinit var rebuilder: RemoteInputNotificationRebuilder
@Mock private lateinit var remoteInputManager: NotificationRemoteInputManager
@Mock private lateinit var mainHandler: Handler
@@ -84,9 +93,6 @@
listener = withArgCaptor {
verify(remoteInputManager).setRemoteInputListener(capture())
}
- collectionListener = withArgCaptor {
- verify(pipeline).addCollectionListener(capture())
- }
entry1 = NotificationEntryBuilder().setId(1).build()
entry2 = NotificationEntryBuilder().setId(2).build()
`when`(rebuilder.rebuildForCanceledSmartReplies(any())).thenReturn(sbn)
@@ -98,16 +104,23 @@
val remoteInputHistoryExtender get() = coordinator.mRemoteInputHistoryExtender
val smartReplyHistoryExtender get() = coordinator.mSmartReplyHistoryExtender
+ val collectionListeners get() = captureMany {
+ verify(pipeline, times(1)).addCollectionListener(capture())
+ }
+
@Test
fun testRemoteInputActive() {
`when`(remoteInputManager.isRemoteInputActive(entry1)).thenReturn(true)
assertThat(remoteInputActiveExtender.maybeExtendLifetime(entry1, 0)).isTrue()
- assertThat(remoteInputHistoryExtender.maybeExtendLifetime(entry1, 0)).isFalse()
- assertThat(smartReplyHistoryExtender.maybeExtendLifetime(entry1, 0)).isFalse()
+ if (!lifetimeExtensionRefactor()) {
+ assertThat(remoteInputHistoryExtender.maybeExtendLifetime(entry1, 0)).isFalse()
+ assertThat(smartReplyHistoryExtender.maybeExtendLifetime(entry1, 0)).isFalse()
+ }
assertThat(listener.isNotificationKeptForRemoteInputHistory(entry1.key)).isFalse()
}
@Test
+ @DisableFlags(FLAG_LIFETIME_EXTENSION_REFACTOR)
fun testRemoteInputHistory() {
`when`(remoteInputManager.shouldKeepForRemoteInputHistory(entry1)).thenReturn(true)
assertThat(remoteInputActiveExtender.maybeExtendLifetime(entry1, 0)).isFalse()
@@ -117,6 +130,7 @@
}
@Test
+ @DisableFlags(FLAG_LIFETIME_EXTENSION_REFACTOR)
fun testSmartReplyHistory() {
`when`(remoteInputManager.shouldKeepForSmartReplyHistory(entry1)).thenReturn(true)
assertThat(remoteInputActiveExtender.maybeExtendLifetime(entry1, 0)).isFalse()
@@ -142,4 +156,81 @@
verify(lifetimeExtensionCallback).onEndLifetimeExtension(remoteInputActiveExtender, entry1)
assertThat(remoteInputActiveExtender.isExtending(entry1.key)).isFalse()
}
+
+ @Test
+ @EnableFlags(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ fun testOnlyRemoteInputActiveLifetimeExtenderExtends() {
+ `when`(remoteInputManager.isRemoteInputActive(entry1)).thenReturn(true)
+ assertThat(remoteInputActiveExtender.maybeExtendLifetime(entry1, 0)).isTrue()
+ assertThat(remoteInputActiveExtender.isExtending(entry1.key)).isTrue()
+
+ listener.onPanelCollapsed()
+ assertThat(remoteInputActiveExtender.isExtending(entry1.key)).isFalse()
+
+ // Checks that lifetimeExtensionCallback is only called the expected number of times,
+ // by the remoteInputActiveExtender.
+ // Checks that the remote input history extender and smart reply history extenders
+ // aren't attached to the pipeline.
+ verify(lifetimeExtensionCallback, times(1)).onEndLifetimeExtension(any(), any())
+ }
+
+ @Test
+ @EnableFlags(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ fun testRemoteInputLifetimeExtensionListenerTrigger() {
+ // Create notification with LIFETIME_EXTENDED_BY_DIRECT_REPLY flag.
+ val entry = NotificationEntryBuilder()
+ .setId(3)
+ .setTag("entry")
+ .setFlag(mContext, Notification.FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY, true)
+ .build()
+ `when`(remoteInputManager.shouldKeepForRemoteInputHistory(entry)).thenReturn(true)
+ `when`(remoteInputManager.shouldKeepForSmartReplyHistory(entry)).thenReturn(false)
+
+ collectionListeners.forEach {
+ it.onEntryUpdated(entry, true)
+ }
+
+ verify(rebuilder, times(1)).rebuildForRemoteInputReply(entry)
+ }
+
+ @Test
+ @EnableFlags(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ fun testSmartReplyLifetimeExtensionListenerTrigger() {
+ // Create notification with LIFETIME_EXTENDED_BY_DIRECT_REPLY flag.
+ val entry = NotificationEntryBuilder()
+ .setId(3)
+ .setTag("entry")
+ .setFlag(mContext, Notification.FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY, true)
+ .build()
+ `when`(remoteInputManager.shouldKeepForRemoteInputHistory(entry)).thenReturn(false)
+ `when`(remoteInputManager.shouldKeepForSmartReplyHistory(entry)).thenReturn(true)
+ collectionListeners.forEach {
+ it.onEntryUpdated(entry, true)
+ }
+
+
+ verify(rebuilder, times(1)).rebuildForCanceledSmartReplies(entry)
+ verify(smartReplyController, times(1)).stopSending(entry)
+ }
+
+ @Test
+ @EnableFlags(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ fun testLifetimeExtensionListenerClearsRemoteInputs() {
+ // Create notification with LIFETIME_EXTENDED_BY_DIRECT_REPLY flag.
+ val entry = NotificationEntryBuilder()
+ .setId(3)
+ .setTag("entry")
+ .setFlag(mContext, Notification.FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY, false)
+ .build()
+ entry.remoteInputs = ArrayList<RemoteInputHistoryItem>()
+ entry.remoteInputs.add(RemoteInputHistoryItem("Test Text"))
+ `when`(remoteInputManager.shouldKeepForRemoteInputHistory(entry)).thenReturn(false)
+ `when`(remoteInputManager.shouldKeepForSmartReplyHistory(entry)).thenReturn(false)
+
+ collectionListeners.forEach {
+ it.onEntryUpdated(entry, true)
+ }
+
+ assertThat(entry.remoteInputs).isNull()
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt
index ff882b1..9055ba4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/ui/viewmodel/SharedNotificationContainerViewModelTest.kt
@@ -138,7 +138,8 @@
configurationRepository.onAnyConfigurationChange()
- assertThat(dimens!!.paddingTop).isEqualTo(30)
+ // Should directly use the header height (flagged off value)
+ assertThat(dimens!!.paddingTop).isEqualTo(10)
}
@Test
@@ -154,7 +155,8 @@
configurationRepository.onAnyConfigurationChange()
- assertThat(dimens!!.paddingTop).isEqualTo(40)
+ // Should directly use the header height (flagged on value)
+ assertThat(dimens!!.paddingTop).isEqualTo(5)
}
@Test
@@ -456,8 +458,8 @@
)
runCurrent()
- // Top should be equal to bounds (1) + padding adjustment (30)
- assertThat(bounds).isEqualTo(NotificationContainerBounds(top = 31f, bottom = 2f))
+ // Top should be equal to bounds (1) - padding adjustment (10)
+ assertThat(bounds).isEqualTo(NotificationContainerBounds(top = -9f, bottom = 2f))
}
@Test
@@ -483,8 +485,8 @@
)
runCurrent()
- // Top should be equal to bounds (1) + padding adjustment (40)
- assertThat(bounds).isEqualTo(NotificationContainerBounds(top = 41f, bottom = 2f))
+ // Top should be equal to bounds (1) - padding adjustment (5)
+ assertThat(bounds).isEqualTo(NotificationContainerBounds(top = -4f, bottom = 2f))
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java
index bbf9a6b..38698f8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardClockPositionAlgorithmTest.java
@@ -45,6 +45,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;
+import org.mockito.quality.Strictness;
@SmallTest
@RunWith(AndroidTestingRunner.class)
@@ -80,6 +81,7 @@
public void setUp() {
MockitoAnnotations.initMocks(this);
mStaticMockSession = mockitoSession()
+ .strictness(Strictness.WARN)
.mockStatic(BurnInHelperKt.class)
.mockStatic(LargeScreenHeaderHelper.class)
.startMocking();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
index b3708ba..41b959e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LegacyNotificationIconAreaControllerImplTest.java
@@ -26,6 +26,7 @@
import androidx.test.filters.SmallTest;
+import com.android.systemui.Flags;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.demomode.DemoModeController;
import com.android.systemui.flags.FeatureFlags;
@@ -118,6 +119,7 @@
@Test
public void testAppearResetsTranslation() {
+ mSetFlagsRule.disableFlags(Flags.FLAG_KEYGUARD_SHADE_MIGRATION_NSSL);
mController.setupAodIcons(mAodIcons);
when(mDozeParameters.shouldControlScreenOff()).thenReturn(false);
mController.appearAodIcons();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt
index 6eb1c1a..4293a27 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewTest.kt
@@ -42,6 +42,7 @@
import org.junit.Test
import org.mockito.Mockito.never
import org.mockito.Mockito.spy
+import org.mockito.Mockito.times
import org.mockito.Mockito.verify
@SmallTest
@@ -145,6 +146,18 @@
}
@Test
+ fun onConfigurationChanged_multipleCalls_flagEnabled_updatesWindowHeightMultipleTimes() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_TRUNCATED_STATUS_BAR_ICONS_FIX)
+
+ view.onConfigurationChanged(Configuration())
+ view.onConfigurationChanged(Configuration())
+ view.onConfigurationChanged(Configuration())
+ view.onConfigurationChanged(Configuration())
+
+ verify(windowController, times(4)).refreshStatusBarHeight()
+ }
+
+ @Test
fun onConfigurationChanged_flagDisabled_doesNotUpdateWindowHeight() {
mSetFlagsRule.disableFlags(Flags.FLAG_TRUNCATED_STATUS_BAR_ICONS_FIX)
@@ -154,6 +167,18 @@
}
@Test
+ fun onConfigurationChanged_multipleCalls_flagDisabled_doesNotUpdateWindowHeight() {
+ mSetFlagsRule.disableFlags(Flags.FLAG_TRUNCATED_STATUS_BAR_ICONS_FIX)
+
+ view.onConfigurationChanged(Configuration())
+ view.onConfigurationChanged(Configuration())
+ view.onConfigurationChanged(Configuration())
+ view.onConfigurationChanged(Configuration())
+
+ verify(windowController, never()).refreshStatusBarHeight()
+ }
+
+ @Test
fun onAttachedToWindow_updatesLeftTopRightPaddingsBasedOnInsets() {
val insets = Insets.of(/* left = */ 10, /* top = */ 20, /* right = */ 30, /* bottom = */ 40)
whenever(contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation())
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
index 54d3607..3da5ab9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
@@ -131,7 +131,7 @@
@Mock
private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(this);
private List<StatusBarWindowStateListener> mStatusBarWindowStateListeners = new ArrayList<>();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/MultiSourceMinAlphaControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/MultiSourceMinAlphaControllerTest.kt
index 2ce060c..997c00c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/MultiSourceMinAlphaControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/MultiSourceMinAlphaControllerTest.kt
@@ -42,7 +42,7 @@
private val multiSourceMinAlphaController =
MultiSourceMinAlphaController(view, initialAlpha = INITIAL_ALPHA)
- @get:Rule val animatorTestRule = AnimatorTestRule()
+ @get:Rule val animatorTestRule = AnimatorTestRule(this)
@Before
fun setup() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
index 658e6b0..13167b2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
@@ -112,7 +112,7 @@
private final UiEventLoggerFake mUiEventLoggerFake = new UiEventLoggerFake();
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(this);
@Before
public void setUp() throws Exception {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/surfaceeffects/loadingeffect/LoadingEffectTest.kt b/packages/SystemUI/tests/src/com/android/systemui/surfaceeffects/loadingeffect/LoadingEffectTest.kt
new file mode 100644
index 0000000..7c36a85
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/surfaceeffects/loadingeffect/LoadingEffectTest.kt
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.surfaceeffects.loadingeffect
+
+import android.graphics.Paint
+import android.graphics.RenderEffect
+import android.testing.AndroidTestingRunner
+import androidx.test.filters.SmallTest
+import com.android.systemui.model.SysUiStateTest
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.AnimationState
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.AnimationState.EASE_IN
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.AnimationState.EASE_OUT
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.AnimationState.MAIN
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.AnimationState.NOT_PLAYING
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.AnimationStateChangedCallback
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.PaintDrawCallback
+import com.android.systemui.surfaceeffects.loadingeffect.LoadingEffect.Companion.RenderEffectDrawCallback
+import com.android.systemui.surfaceeffects.turbulencenoise.TurbulenceNoiseAnimationConfig
+import com.android.systemui.surfaceeffects.turbulencenoise.TurbulenceNoiseShader
+import com.android.systemui.util.concurrency.FakeExecutor
+import com.android.systemui.util.time.FakeSystemClock
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+class LoadingEffectTest : SysUiStateTest() {
+
+ private val fakeSystemClock = FakeSystemClock()
+ private val fakeExecutor = FakeExecutor(fakeSystemClock)
+
+ @Test
+ fun play_paintCallback_triggersDrawCallback() {
+ var paintFromCallback: Paint? = null
+ val drawCallback =
+ object : PaintDrawCallback {
+ override fun onDraw(loadingPaint: Paint) {
+ paintFromCallback = loadingPaint
+ }
+ }
+ val loadingEffect =
+ LoadingEffect(
+ baseType = TurbulenceNoiseShader.Companion.Type.SIMPLEX_NOISE,
+ TurbulenceNoiseAnimationConfig(),
+ paintCallback = drawCallback,
+ animationStateChangedCallback = null
+ )
+
+ fakeExecutor.execute {
+ assertThat(paintFromCallback).isNull()
+
+ loadingEffect.play()
+ fakeSystemClock.advanceTime(500L)
+
+ assertThat(paintFromCallback).isNotNull()
+ }
+ }
+
+ @Test
+ fun play_renderEffectCallback_triggersDrawCallback() {
+ var renderEffectFromCallback: RenderEffect? = null
+ val drawCallback =
+ object : RenderEffectDrawCallback {
+ override fun onDraw(loadingRenderEffect: RenderEffect) {
+ renderEffectFromCallback = loadingRenderEffect
+ }
+ }
+ val loadingEffect =
+ LoadingEffect(
+ baseType = TurbulenceNoiseShader.Companion.Type.SIMPLEX_NOISE,
+ TurbulenceNoiseAnimationConfig(),
+ renderEffectCallback = drawCallback,
+ animationStateChangedCallback = null
+ )
+
+ fakeExecutor.execute {
+ assertThat(renderEffectFromCallback).isNull()
+
+ loadingEffect.play()
+ fakeSystemClock.advanceTime(500L)
+
+ assertThat(renderEffectFromCallback).isNotNull()
+ }
+ }
+
+ @Test
+ fun play_animationStateChangesInOrder() {
+ val config = TurbulenceNoiseAnimationConfig()
+ val expectedStates = arrayOf(NOT_PLAYING, EASE_IN, MAIN, EASE_OUT, NOT_PLAYING)
+ val actualStates = mutableListOf(NOT_PLAYING)
+ val stateChangedCallback =
+ object : AnimationStateChangedCallback {
+ override fun onStateChanged(oldState: AnimationState, newState: AnimationState) {
+ actualStates.add(newState)
+ }
+ }
+ val drawCallback =
+ object : PaintDrawCallback {
+ override fun onDraw(loadingPaint: Paint) {}
+ }
+ val loadingEffect =
+ LoadingEffect(
+ baseType = TurbulenceNoiseShader.Companion.Type.SIMPLEX_NOISE,
+ config,
+ paintCallback = drawCallback,
+ stateChangedCallback
+ )
+
+ val timeToAdvance =
+ config.easeInDuration + config.maxDuration + config.easeOutDuration + 100
+
+ fakeExecutor.execute {
+ loadingEffect.play()
+
+ fakeSystemClock.advanceTime(timeToAdvance.toLong())
+
+ assertThat(actualStates).isEqualTo(expectedStates)
+ }
+ }
+
+ @Test
+ fun play_alreadyPlaying_playsOnlyOnce() {
+ val config = TurbulenceNoiseAnimationConfig()
+ var numPlay = 0
+ val stateChangedCallback =
+ object : AnimationStateChangedCallback {
+ override fun onStateChanged(oldState: AnimationState, newState: AnimationState) {
+ if (oldState == NOT_PLAYING && newState == EASE_IN) {
+ numPlay++
+ }
+ }
+ }
+ val drawCallback =
+ object : PaintDrawCallback {
+ override fun onDraw(loadingPaint: Paint) {}
+ }
+ val loadingEffect =
+ LoadingEffect(
+ baseType = TurbulenceNoiseShader.Companion.Type.SIMPLEX_NOISE,
+ config,
+ paintCallback = drawCallback,
+ stateChangedCallback
+ )
+
+ fakeExecutor.execute {
+ assertThat(numPlay).isEqualTo(0)
+
+ loadingEffect.play()
+ loadingEffect.play()
+ loadingEffect.play()
+ loadingEffect.play()
+ loadingEffect.play()
+
+ assertThat(numPlay).isEqualTo(1)
+ }
+ }
+
+ @Test
+ fun finish_finishesLoadingEffect() {
+ val config = TurbulenceNoiseAnimationConfig(maxDuration = 1000f)
+ val drawCallback =
+ object : PaintDrawCallback {
+ override fun onDraw(loadingPaint: Paint) {}
+ }
+ var isFinished = false
+ val stateChangedCallback =
+ object : AnimationStateChangedCallback {
+ override fun onStateChanged(oldState: AnimationState, newState: AnimationState) {
+ if (oldState == MAIN && newState == NOT_PLAYING) {
+ isFinished = true
+ }
+ }
+ }
+ val loadingEffect =
+ LoadingEffect(
+ baseType = TurbulenceNoiseShader.Companion.Type.SIMPLEX_NOISE,
+ config,
+ paintCallback = drawCallback,
+ stateChangedCallback
+ )
+
+ fakeExecutor.execute {
+ assertThat(isFinished).isFalse()
+
+ loadingEffect.play()
+ fakeSystemClock.advanceTime(config.easeInDuration.toLong() + 500L)
+
+ assertThat(isFinished).isFalse()
+
+ loadingEffect.finish()
+
+ assertThat(isFinished).isTrue()
+ }
+ }
+
+ @Test
+ fun finish_notMainState_hasNoEffect() {
+ val config = TurbulenceNoiseAnimationConfig(maxDuration = 1000f)
+ val drawCallback =
+ object : PaintDrawCallback {
+ override fun onDraw(loadingPaint: Paint) {}
+ }
+ var isFinished = false
+ val stateChangedCallback =
+ object : AnimationStateChangedCallback {
+ override fun onStateChanged(oldState: AnimationState, newState: AnimationState) {
+ if (oldState == MAIN && newState == NOT_PLAYING) {
+ isFinished = true
+ }
+ }
+ }
+ val loadingEffect =
+ LoadingEffect(
+ baseType = TurbulenceNoiseShader.Companion.Type.SIMPLEX_NOISE,
+ config,
+ paintCallback = drawCallback,
+ stateChangedCallback
+ )
+
+ fakeExecutor.execute {
+ assertThat(isFinished).isFalse()
+
+ loadingEffect.finish()
+
+ assertThat(isFinished).isFalse()
+ }
+ }
+
+ @Test
+ fun getNoiseOffset_returnsNoiseOffset() {
+ val expectedNoiseOffset = arrayOf(0.1f, 0.2f, 0.3f)
+ val config =
+ TurbulenceNoiseAnimationConfig(
+ noiseOffsetX = expectedNoiseOffset[0],
+ noiseOffsetY = expectedNoiseOffset[1],
+ noiseOffsetZ = expectedNoiseOffset[2]
+ )
+ val drawCallback =
+ object : PaintDrawCallback {
+ override fun onDraw(loadingPaint: Paint) {}
+ }
+ val loadingEffect =
+ LoadingEffect(
+ baseType = TurbulenceNoiseShader.Companion.Type.SIMPLEX_NOISE,
+ config,
+ paintCallback = drawCallback,
+ animationStateChangedCallback = null
+ )
+
+ assertThat(loadingEffect.getNoiseOffset()).isEqualTo(expectedNoiseOffset)
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
index 8a33778..25a0bc4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
@@ -157,7 +157,7 @@
private FakeSettings mSecureSettings;
@Rule
- public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule();
+ public final AnimatorTestRule mAnimatorTestRule = new AnimatorTestRule(this);
@Before
public void setup() throws Exception {
diff --git a/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java b/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java
index 1afe56f..5860c2d 100644
--- a/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java
+++ b/packages/SystemUI/tests/utils/src/android/animation/AnimatorTestRule.java
@@ -16,14 +16,21 @@
package android.animation;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
import android.animation.AnimationHandler.AnimationFrameCallback;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Looper;
import android.os.SystemClock;
+import android.testing.TestableLooper;
+import android.testing.TestableLooper.RunnableWithException;
import android.util.AndroidRuntimeException;
import android.util.Singleton;
import android.view.Choreographer;
+import android.view.animation.AnimationUtils;
+
+import androidx.test.platform.app.InstrumentationRegistry;
import com.android.internal.util.Preconditions;
@@ -74,25 +81,31 @@
return new TestHandler();
}
};
+ private final Object mTest;
private final long mStartTime;
private long mTotalTimeDelta = 0;
+ private volatile boolean mCanLockAnimationClock;
+ private Looper mLooperWithLockedAnimationClock;
/**
- * Construct an AnimatorTestRule with a custom start time.
- * @see #AnimatorTestRule()
+ * Construct an AnimatorTestRule with access to the test instance and a custom start time.
+ * @see #AnimatorTestRule(Object)
*/
- public AnimatorTestRule(long startTime) {
+ public AnimatorTestRule(Object test, long startTime) {
+ mTest = test;
mStartTime = startTime;
}
/**
- * Construct an AnimatorTestRule with a start time of {@link SystemClock#uptimeMillis()}.
- * Initializing the start time with this clock reduces the discrepancies with various internals
- * of classes like ValueAnimator which can sometimes read that clock via
- * {@link android.view.animation.AnimationUtils#currentAnimationTimeMillis()}.
+ * Construct an AnimatorTestRule for the given test instance with a start time of
+ * {@link SystemClock#uptimeMillis()}. Initializing the start time with this clock reduces the
+ * discrepancies with various internals of classes like ValueAnimator which can sometimes read
+ * that clock via {@link android.view.animation.AnimationUtils#currentAnimationTimeMillis()}.
+ *
+ * @param test the test instance used to access the {@link TestableLooper} used by the class.
*/
- public AnimatorTestRule() {
- this(SystemClock.uptimeMillis());
+ public AnimatorTestRule(Object test) {
+ this(test, SystemClock.uptimeMillis());
}
@NonNull
@@ -102,10 +115,16 @@
@Override
public void evaluate() throws Throwable {
final TestHandler testHandler = mTestHandler.get();
- AnimationHandler objAtStart = AnimationHandler.setTestHandler(testHandler);
+ final AnimationHandler objAtStart = AnimationHandler.setTestHandler(testHandler);
+ final RunnableWithException lockClock =
+ wrapWithRunBlocking(new LockAnimationClockRunnable());
+ final RunnableWithException unlockClock =
+ wrapWithRunBlocking(new UnlockAnimationClockRunnable());
try {
+ lockClock.run();
base.evaluate();
} finally {
+ unlockClock.run();
AnimationHandler objAtEnd = AnimationHandler.setTestHandler(objAtStart);
if (testHandler != objAtEnd) {
// pass or fail, inner logic not restoring the handler needs to be reported.
@@ -118,6 +137,78 @@
};
}
+ private RunnableWithException wrapWithRunBlocking(RunnableWithException runnable) {
+ RunnableWithException wrapped = TestableLooper.wrapWithRunBlocking(mTest, runnable);
+ if (wrapped != null) {
+ return wrapped;
+ }
+ return () -> runOnMainThrowing(runnable);
+ }
+
+ private static void runOnMainThrowing(RunnableWithException runnable) throws Exception {
+ if (Looper.myLooper() == Looper.getMainLooper()) {
+ runnable.run();
+ } else {
+ final Throwable[] throwableBox = new Throwable[1];
+ InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
+ try {
+ runnable.run();
+ } catch (Throwable t) {
+ throwableBox[0] = t;
+ }
+ });
+ if (throwableBox[0] == null) {
+ return;
+ } else if (throwableBox[0] instanceof RuntimeException ex) {
+ throw ex;
+ } else if (throwableBox[0] instanceof Error err) {
+ throw err;
+ } else {
+ throw new RuntimeException(throwableBox[0]);
+ }
+ }
+ }
+
+ private class LockAnimationClockRunnable implements RunnableWithException {
+ @Override
+ public void run() {
+ mLooperWithLockedAnimationClock = Looper.myLooper();
+ mCanLockAnimationClock = true;
+ lockAnimationClockToCurrentTime();
+ }
+ }
+
+ private class UnlockAnimationClockRunnable implements RunnableWithException {
+ @Override
+ public void run() {
+ mCanLockAnimationClock = false;
+ mLooperWithLockedAnimationClock = null;
+ AnimationUtils.unlockAnimationClock();
+ }
+ }
+
+ private void lockAnimationClockToCurrentTime() {
+ if (!mCanLockAnimationClock) {
+ throw new AssertionError("Unable to lock the animation clock; "
+ + "has the test started? already finished?");
+ }
+ if (mLooperWithLockedAnimationClock != Looper.myLooper()) {
+ throw new AssertionError("Animation clock being locked on " + Looper.myLooper()
+ + " but should only be locked on " + mLooperWithLockedAnimationClock);
+ }
+ long desiredTime = getCurrentTime();
+ AnimationUtils.lockAnimationClock(desiredTime);
+ if (!mCanLockAnimationClock) {
+ AnimationUtils.unlockAnimationClock();
+ throw new AssertionError("Threading error when locking the animation clock");
+ }
+ long outputTime = AnimationUtils.currentAnimationTimeMillis();
+ if (outputTime != desiredTime) {
+ throw new AssertionError("currentAnimationTimeMillis() is " + outputTime
+ + " after locking to " + desiredTime);
+ }
+ }
+
/**
* If any new {@link Animator}s have been registered since the last time the frame time was
* advanced, initialize them with the current frame time. Failing to do this will result in the
@@ -178,6 +269,7 @@
// advance time
mTotalTimeDelta += timeDelta;
}
+ lockAnimationClockToCurrentTime();
if (preFrameAction != null) {
preFrameAction.accept(timeDelta);
// After letting other code run, clear any new callbacks to avoid double-ticking them
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/animation/AnimatorTestRule.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/animation/AnimatorTestRule.kt
index ba9c5ed..e2fc44f 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/animation/AnimatorTestRule.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/animation/AnimatorTestRule.kt
@@ -26,12 +26,16 @@
* A rule that wraps both [androidx.core.animation.AnimatorTestRule] and
* [android.animation.AnimatorTestRule] such that the clocks of the two animation handlers can be
* advanced together.
+ *
+ * @param test the instance of the test used to look up the TestableLooper. If a TestableLooper is
+ * found, the time can only be advanced on that thread; otherwise the time must be advanced on the
+ * main thread.
*/
-class AnimatorTestRule : TestRule {
+class AnimatorTestRule(test: Any?) : TestRule {
// Create the androidx rule, which initializes start time to SystemClock.uptimeMillis(),
// then copy that time to the platform rule so that the two clocks are in sync.
private val androidxRule = androidx.core.animation.AnimatorTestRule()
- private val platformRule = android.animation.AnimatorTestRule(androidxRule.startTime)
+ private val platformRule = android.animation.AnimatorTestRule(test, androidxRule.startTime)
private val advanceAndroidXTimeBy =
Consumer<Long> { timeDelta -> androidxRule.advanceTimeBy(timeDelta) }
diff --git a/ravenwood/mockito/Android.bp b/ravenwood/mockito/Android.bp
index a74bca4..95c7394 100644
--- a/ravenwood/mockito/Android.bp
+++ b/ravenwood/mockito/Android.bp
@@ -13,6 +13,9 @@
srcs: [
"test/**/*.java",
],
+ exclude_srcs: [
+ "test/**/*DeviceOnly*.java",
+ ],
static_libs: [
"junit",
"truth",
@@ -31,6 +34,9 @@
srcs: [
"test/**/*.java",
],
+ exclude_srcs: [
+ "test/**/*RavenwoodOnly*.java",
+ ],
static_libs: [
"junit",
"truth",
diff --git a/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoDeviceOnlyTest.java b/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoDeviceOnlyTest.java
new file mode 100644
index 0000000..d02fe69
--- /dev/null
+++ b/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoDeviceOnlyTest.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.ravenwood.mockito;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.ActivityManager;
+import android.platform.test.ravenwood.RavenwoodRule;
+
+import com.android.dx.mockito.inline.extended.ExtendedMockito;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.quality.Strictness;
+
+public class RavenwoodMockitoDeviceOnlyTest {
+ @Rule public final RavenwoodRule mRavenwood = new RavenwoodRule();
+
+ @Test
+ public void testStaticMockOnDevice() {
+ var mockingSession = ExtendedMockito.mockitoSession()
+ .strictness(Strictness.LENIENT)
+ .mockStatic(ActivityManager.class)
+ .startMocking();
+ try {
+ ExtendedMockito.doReturn(true).when(ActivityManager::isUserAMonkey);
+
+ assertThat(ActivityManager.isUserAMonkey()).isEqualTo(true);
+ } finally {
+ mockingSession.finishMocking();
+ }
+ }
+}
diff --git a/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoRavenwoodOnlyTest.java b/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoRavenwoodOnlyTest.java
new file mode 100644
index 0000000..0c137d5
--- /dev/null
+++ b/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoRavenwoodOnlyTest.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.ravenwood.mockito;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.ActivityManager;
+import android.platform.test.ravenwood.RavenwoodRule;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+public class RavenwoodMockitoRavenwoodOnlyTest {
+ @Rule public final RavenwoodRule mRavenwood = new RavenwoodRule();
+
+ @Test
+ public void testStaticMockOnRavenwood() {
+ try (MockedStatic<ActivityManager> am = Mockito.mockStatic(ActivityManager.class)) {
+ am.when(ActivityManager::isUserAMonkey).thenReturn(true);
+ assertThat(ActivityManager.isUserAMonkey()).isEqualTo(true);
+ }
+ }
+}
diff --git a/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoTest.java b/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoTest.java
index 1284d64..9566710 100644
--- a/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoTest.java
+++ b/ravenwood/mockito/test/com/android/ravenwood/mockito/RavenwoodMockitoTest.java
@@ -31,28 +31,6 @@
public class RavenwoodMockitoTest {
@Rule public final RavenwoodRule mRavenwood = new RavenwoodRule();
-
-// Use this to mock static methods, which isn't supported by mockito 2.
-// Mockito supports static mocking since 3.4.0:
-// See: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#48
-
-// private MockitoSession mMockingSession;
-//
-// @Before
-// public void setUp() {
-// mMockingSession = mockitoSession()
-// .strictness(Strictness.LENIENT)
-// .mockStatic(RavenwoodMockitoTest.class)
-// .startMocking();
-// }
-//
-// @After
-// public void tearDown() {
-// if (mMockingSession != null) {
-// mMockingSession.finishMocking();
-// }
-// }
-
@Test
public void testMockJdkClass() {
Process object = mock(Process.class);
diff --git a/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java b/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java
index b64c74e..af47ed2 100644
--- a/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java
+++ b/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java
@@ -42,10 +42,12 @@
import android.accessibilityservice.AccessibilityTrace;
import android.accessibilityservice.IAccessibilityServiceClient;
import android.accessibilityservice.IAccessibilityServiceConnection;
+import android.accessibilityservice.IBrailleDisplayController;
import android.accessibilityservice.MagnificationConfig;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
@@ -58,6 +60,7 @@
import android.hardware.HardwareBuffer;
import android.hardware.display.DisplayManager;
import android.hardware.display.DisplayManagerInternal;
+import android.hardware.usb.UsbDevice;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
@@ -2776,4 +2779,23 @@
t.close();
mOverlays.clear();
}
+
+ @Override
+ @SuppressLint("AndroidFrameworkRequiresPermission") // Unsupported in Abstract class
+ public void connectBluetoothBrailleDisplay(String bluetoothAddress,
+ IBrailleDisplayController controller) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void connectUsbBrailleDisplay(UsbDevice usbDevice,
+ IBrailleDisplayController controller) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ @SuppressLint("AndroidFrameworkRequiresPermission") // Unsupported in Abstract class
+ public void setTestBrailleDisplayData(List<Bundle> brailleDisplays) {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java
index 5ebe161..b90a66a 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java
@@ -26,16 +26,25 @@
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.AccessibilityTrace;
+import android.accessibilityservice.BrailleDisplayController;
import android.accessibilityservice.IAccessibilityServiceClient;
+import android.accessibilityservice.IBrailleDisplayController;
import android.accessibilityservice.TouchInteractionController;
+import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
+import android.annotation.SuppressLint;
import android.annotation.UserIdInt;
import android.app.PendingIntent;
+import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ParceledListSlice;
+import android.hardware.usb.UsbDevice;
+import android.hardware.usb.UsbManager;
import android.os.Binder;
+import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
@@ -44,6 +53,7 @@
import android.os.Trace;
import android.os.UserHandle;
import android.provider.Settings;
+import android.text.TextUtils;
import android.util.Slog;
import android.view.Display;
import android.view.MotionEvent;
@@ -55,6 +65,8 @@
import com.android.server.wm.WindowManagerInternal;
import java.lang.ref.WeakReference;
+import java.util.List;
+import java.util.Objects;
import java.util.Set;
/**
@@ -82,6 +94,9 @@
final Intent mIntent;
final ActivityTaskManagerInternal mActivityTaskManagerService;
+ private BrailleDisplayConnection mBrailleDisplayConnection;
+ private List<Bundle> mTestBrailleDisplays = null;
+
private final Handler mMainHandler;
private static final class AccessibilityInputMethodSessionCallback
@@ -448,6 +463,16 @@
}
}
+ @Override
+ public void resetLocked() {
+ super.resetLocked();
+ if (android.view.accessibility.Flags.brailleDisplayHid()) {
+ if (mBrailleDisplayConnection != null) {
+ mBrailleDisplayConnection.disconnect();
+ }
+ }
+ }
+
public boolean isAccessibilityButtonAvailableLocked(AccessibilityUserState userState) {
// If the service does not request the accessibility button, it isn't available
if (!mRequestAccessibilityButton) {
@@ -640,4 +665,123 @@
}
}
}
+
+ private void checkAccessibilityAccessLocked() {
+ if (!hasRightsToCurrentUserLocked()
+ || !mSecurityPolicy.checkAccessibilityAccess(this)) {
+ throw new SecurityException("Caller does not have accessibility access");
+ }
+ }
+
+ /**
+ * Sets up a BrailleDisplayConnection interface for the requested Bluetooth-connected
+ * Braille display.
+ *
+ * @param bluetoothAddress The address from
+ * {@link android.bluetooth.BluetoothDevice#getAddress()}.
+ */
+ @Override
+ @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
+ public void connectBluetoothBrailleDisplay(
+ @NonNull String bluetoothAddress, @NonNull IBrailleDisplayController controller) {
+ if (!android.view.accessibility.Flags.brailleDisplayHid()) {
+ throw new IllegalStateException("Flag BRAILLE_DISPLAY_HID not enabled");
+ }
+ Objects.requireNonNull(bluetoothAddress);
+ Objects.requireNonNull(controller);
+ mContext.enforceCallingPermission(Manifest.permission.BLUETOOTH_CONNECT,
+ "Missing BLUETOOTH_CONNECT permission");
+ if (!BluetoothAdapter.checkBluetoothAddress(bluetoothAddress)) {
+ throw new IllegalArgumentException(
+ bluetoothAddress + " is not a valid Bluetooth address");
+ }
+ synchronized (mLock) {
+ checkAccessibilityAccessLocked();
+ if (mBrailleDisplayConnection != null) {
+ throw new IllegalStateException(
+ "This service already has a connected Braille display");
+ }
+ BrailleDisplayConnection connection = new BrailleDisplayConnection(mLock, this);
+ if (mTestBrailleDisplays != null) {
+ connection.setTestData(mTestBrailleDisplays);
+ }
+ connection.connectLocked(
+ bluetoothAddress, BrailleDisplayConnection.BUS_BLUETOOTH, controller);
+ }
+ }
+
+ /**
+ * Sets up a BrailleDisplayConnection interface for the requested USB-connected
+ * Braille display.
+ *
+ * <p>The caller package must already have USB permission for this {@link UsbDevice}.
+ */
+ @SuppressLint("MissingPermission") // system_server has the required MANAGE_USB permission
+ @Override
+ @NonNull
+ public void connectUsbBrailleDisplay(@NonNull UsbDevice usbDevice,
+ @NonNull IBrailleDisplayController controller) {
+ if (!android.view.accessibility.Flags.brailleDisplayHid()) {
+ throw new IllegalStateException("Flag BRAILLE_DISPLAY_HID not enabled");
+ }
+ Objects.requireNonNull(usbDevice);
+ Objects.requireNonNull(controller);
+ final UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
+ final String usbSerialNumber;
+ final int uid = Binder.getCallingUid();
+ final int pid = Binder.getCallingPid();
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ if (usbManager == null || !usbManager.hasPermission(
+ usbDevice, mComponentName.getPackageName(), /*pid=*/ pid, /*uid=*/ uid)) {
+ throw new SecurityException(
+ "Caller does not have permission to access this UsbDevice");
+ }
+ usbSerialNumber = usbDevice.getSerialNumber();
+ if (TextUtils.isEmpty(usbSerialNumber)) {
+ // If the UsbDevice does not report a serial number for locating the HIDRAW
+ // node then notify connection error ERROR_BRAILLE_DISPLAY_NOT_FOUND.
+ try {
+ controller.onConnectionFailed(BrailleDisplayController.BrailleDisplayCallback
+ .FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND);
+ } catch (RemoteException e) {
+ Slog.e(LOG_TAG, "Error calling onConnectionFailed", e);
+ }
+ return;
+ }
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ synchronized (mLock) {
+ checkAccessibilityAccessLocked();
+ if (mBrailleDisplayConnection != null) {
+ throw new IllegalStateException(
+ "This service already has a connected Braille display");
+ }
+ BrailleDisplayConnection connection = new BrailleDisplayConnection(mLock, this);
+ if (mTestBrailleDisplays != null) {
+ connection.setTestData(mTestBrailleDisplays);
+ }
+ connection.connectLocked(
+ usbSerialNumber, BrailleDisplayConnection.BUS_USB, controller);
+ }
+ }
+
+ @Override
+ @RequiresPermission(Manifest.permission.MANAGE_ACCESSIBILITY)
+ public void setTestBrailleDisplayData(List<Bundle> brailleDisplays) {
+ // Enforce that this TestApi is only called by trusted (test) callers.
+ mContext.enforceCallingPermission(Manifest.permission.MANAGE_ACCESSIBILITY,
+ "Missing MANAGE_ACCESSIBILITY permission");
+ mTestBrailleDisplays = brailleDisplays;
+ }
+
+ void onBrailleDisplayConnectedLocked(BrailleDisplayConnection connection) {
+ mBrailleDisplayConnection = connection;
+ }
+
+ // Reset state when the BrailleDisplayConnection object disconnects itself.
+ void onBrailleDisplayDisconnectedLocked() {
+ mBrailleDisplayConnection = null;
+ }
}
diff --git a/services/accessibility/java/com/android/server/accessibility/BrailleDisplayConnection.java b/services/accessibility/java/com/android/server/accessibility/BrailleDisplayConnection.java
new file mode 100644
index 0000000..1f18e15
--- /dev/null
+++ b/services/accessibility/java/com/android/server/accessibility/BrailleDisplayConnection.java
@@ -0,0 +1,534 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.accessibility;
+
+import static android.accessibilityservice.BrailleDisplayController.BrailleDisplayCallback.FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND;
+import static android.accessibilityservice.BrailleDisplayController.BrailleDisplayCallback.FLAG_ERROR_CANNOT_ACCESS;
+
+import android.accessibilityservice.BrailleDisplayController;
+import android.accessibilityservice.IBrailleDisplayConnection;
+import android.accessibilityservice.IBrailleDisplayController;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.PermissionManuallyEnforced;
+import android.annotation.RequiresNoPermission;
+import android.bluetooth.BluetoothDevice;
+import android.hardware.usb.UsbDevice;
+import android.os.Bundle;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.Process;
+import android.os.RemoteException;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.util.Pair;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+
+/**
+ * This class represents the connection between {@code system_server} and a connected
+ * Braille Display using the Braille Display HID standard (usage page 0x41).
+ */
+class BrailleDisplayConnection extends IBrailleDisplayConnection.Stub {
+ private static final String LOG_TAG = "BrailleDisplayConnection";
+
+ /**
+ * Represents the connection type of a Braille display.
+ *
+ * <p>The integer values must match the kernel's bus type values because this bus type is
+ * used to locate the correct HIDRAW node using data from the kernel. These values come
+ * from the UAPI header file bionic/libc/kernel/uapi/linux/input.h, which is guaranteed
+ * to stay constant.
+ */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(flag = true, prefix = {"BUS_"}, value = {
+ BUS_UNKNOWN,
+ BUS_USB,
+ BUS_BLUETOOTH
+ })
+ @interface BusType {
+ }
+ static final int BUS_UNKNOWN = -1;
+ static final int BUS_USB = 0x03;
+ static final int BUS_BLUETOOTH = 0x05;
+
+ // Access to this static object must be guarded by a lock that is shared for all instances
+ // of this class: the singular Accessibility system_server lock (mLock).
+ private static final Set<File> sConnectedNodes = new ArraySet<>();
+
+ // Used to guard to AIDL methods from concurrent calls.
+ // Lock must match the one used by AccessibilityServiceConnection, which itself
+ // comes from AccessibilityManagerService.
+ private final Object mLock;
+ private final AccessibilityServiceConnection mServiceConnection;
+
+
+ private File mHidrawNode;
+ private IBrailleDisplayController mController;
+
+ private Thread mInputThread;
+ private OutputStream mOutputStream;
+ private HandlerThread mOutputThread;
+
+ // mScanner is not final because tests may modify this to use a test-only scanner.
+ private BrailleDisplayScanner mScanner;
+
+ BrailleDisplayConnection(@NonNull Object lock,
+ @NonNull AccessibilityServiceConnection serviceConnection) {
+ this.mLock = Objects.requireNonNull(lock);
+ this.mScanner = getDefaultNativeScanner(getDefaultNativeInterface());
+ this.mServiceConnection = Objects.requireNonNull(serviceConnection);
+ }
+
+ /**
+ * Interface to scan for properties of connected Braille displays.
+ *
+ * <p>Helps simplify testing Braille Display APIs using test data without requiring
+ * a real Braille display to be connected to the device, by using a test implementation
+ * of this interface.
+ *
+ * @see #getDefaultNativeScanner
+ * @see #setTestData
+ */
+ @VisibleForTesting
+ interface BrailleDisplayScanner {
+ Collection<Path> getHidrawNodePaths();
+
+ byte[] getDeviceReportDescriptor(@NonNull Path path);
+
+ String getUniqueId(@NonNull Path path);
+
+ @BusType
+ int getDeviceBusType(@NonNull Path path);
+ }
+
+ /**
+ * Finds the Braille display HIDRAW node associated with the provided unique ID.
+ *
+ * <p>If found, saves instance state for this connection and starts a thread to
+ * read from the Braille display.
+ *
+ * @param expectedUniqueId The expected unique ID of the device to connect, from
+ * {@link UsbDevice#getSerialNumber()}
+ * or {@link BluetoothDevice#getAddress()}
+ * @param expectedBusType The expected bus type from {@link BusType}.
+ * @param controller Interface containing oneway callbacks used to communicate with the
+ * {@link android.accessibilityservice.BrailleDisplayController}.
+ */
+ void connectLocked(
+ @NonNull String expectedUniqueId,
+ @BusType int expectedBusType,
+ @NonNull IBrailleDisplayController controller) {
+ Objects.requireNonNull(expectedUniqueId);
+ this.mController = Objects.requireNonNull(controller);
+
+ final List<Pair<File, byte[]>> result = new ArrayList<>();
+ final Collection<Path> hidrawNodePaths = mScanner.getHidrawNodePaths();
+ if (hidrawNodePaths == null) {
+ Slog.w(LOG_TAG, "Unable to access the HIDRAW node directory");
+ sendConnectionErrorLocked(FLAG_ERROR_CANNOT_ACCESS);
+ return;
+ }
+ boolean unableToGetDescriptor = false;
+ // For every present HIDRAW device node:
+ for (Path path : hidrawNodePaths) {
+ final byte[] descriptor = mScanner.getDeviceReportDescriptor(path);
+ if (descriptor == null) {
+ unableToGetDescriptor = true;
+ continue;
+ }
+ final String uniqueId = mScanner.getUniqueId(path);
+ if (isBrailleDisplay(descriptor)
+ && mScanner.getDeviceBusType(path) == expectedBusType
+ && expectedUniqueId.equalsIgnoreCase(uniqueId)) {
+ result.add(Pair.create(path.toFile(), descriptor));
+ }
+ }
+
+ // Return success only when exactly one matching device node is found.
+ if (result.size() != 1) {
+ @BrailleDisplayController.BrailleDisplayCallback.ErrorCode int errorCode =
+ FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND;
+ // If we were unable to get some /dev/hidraw* descriptor then tell the accessibility
+ // service that the device may not have proper access to these device nodes.
+ if (unableToGetDescriptor) {
+ Slog.w(LOG_TAG, "Unable to access some HIDRAW node's descriptor");
+ errorCode |= FLAG_ERROR_CANNOT_ACCESS;
+ } else {
+ Slog.w(LOG_TAG,
+ "Unable to find a unique Braille display matching the provided device");
+ }
+ sendConnectionErrorLocked(errorCode);
+ return;
+ }
+
+ this.mHidrawNode = result.get(0).first;
+ final byte[] reportDescriptor = result.get(0).second;
+
+ // Only one connection instance should exist for this hidraw node, across
+ // all currently running accessibility services.
+ if (sConnectedNodes.contains(this.mHidrawNode)) {
+ Slog.w(LOG_TAG,
+ "Unable to find an unused Braille display matching the provided device");
+ sendConnectionErrorLocked(FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND);
+ return;
+ }
+ sConnectedNodes.add(this.mHidrawNode);
+
+ startReadingLocked();
+
+ try {
+ mServiceConnection.onBrailleDisplayConnectedLocked(this);
+ mController.onConnected(this, reportDescriptor);
+ } catch (RemoteException e) {
+ Slog.e(LOG_TAG, "Error calling onConnected", e);
+ disconnect();
+ }
+ }
+
+ private void sendConnectionErrorLocked(
+ @BrailleDisplayController.BrailleDisplayCallback.ErrorCode int errorCode) {
+ try {
+ mController.onConnectionFailed(errorCode);
+ } catch (RemoteException e) {
+ Slog.e(LOG_TAG, "Error calling onConnectionFailed", e);
+ }
+ }
+
+ /** Returns true if this descriptor includes usages for the Braille display usage page 0x41. */
+ private static boolean isBrailleDisplay(byte[] descriptor) {
+ // TODO: b/316036493 - Check that descriptor includes 0x41 reports.
+ return true;
+ }
+
+ /**
+ * Checks that the AccessibilityService that owns this BrailleDisplayConnection
+ * is still connected to the system.
+ *
+ * @throws IllegalStateException if not connected
+ */
+ private void assertServiceIsConnectedLocked() {
+ if (!mServiceConnection.isConnectedLocked()) {
+ throw new IllegalStateException("Accessibility service is not connected");
+ }
+ }
+
+ /**
+ * Disconnects from this Braille display. This object is no longer valid after
+ * this call returns.
+ */
+ @Override
+ // This is a cleanup method, so allow the call even if the calling service was disabled.
+ @RequiresNoPermission
+ public void disconnect() {
+ synchronized (mLock) {
+ closeInputLocked();
+ closeOutputLocked();
+ mServiceConnection.onBrailleDisplayDisconnectedLocked();
+ try {
+ mController.onDisconnected();
+ } catch (RemoteException e) {
+ Slog.e(LOG_TAG, "Error calling onDisconnected");
+ }
+ sConnectedNodes.remove(this.mHidrawNode);
+ }
+ }
+
+ /**
+ * Writes the provided HID bytes to this Braille display.
+ *
+ * <p>Writes are posted to a background thread handler.
+ *
+ * @param buffer The bytes to write to the Braille display. These bytes should be formatted
+ * according to the report descriptor.
+ */
+ @Override
+ @PermissionManuallyEnforced // by assertServiceIsConnectedLocked()
+ public void write(@NonNull byte[] buffer) {
+ Objects.requireNonNull(buffer);
+ if (buffer.length > IBinder.getSuggestedMaxIpcSizeBytes()) {
+ Slog.e(LOG_TAG, "Requested write of size " + buffer.length
+ + " which is larger than maximum " + IBinder.getSuggestedMaxIpcSizeBytes());
+ return;
+ }
+ synchronized (mLock) {
+ assertServiceIsConnectedLocked();
+ if (mOutputThread == null) {
+ try {
+ mOutputStream = new FileOutputStream(mHidrawNode);
+ } catch (FileNotFoundException e) {
+ Slog.e(LOG_TAG, "Unable to create write stream", e);
+ disconnect();
+ return;
+ }
+ mOutputThread = new HandlerThread("BrailleDisplayConnection output thread",
+ Process.THREAD_PRIORITY_BACKGROUND);
+ mOutputThread.setDaemon(true);
+ mOutputThread.start();
+ }
+ // TODO: b/316035785 - Proactively disconnect a misbehaving Braille display by calling
+ // disconnect() if the mOutputThread handler queue grows too large.
+ mOutputThread.getThreadHandler().post(() -> {
+ try {
+ mOutputStream.write(buffer);
+ } catch (IOException e) {
+ Slog.d(LOG_TAG, "Error writing to connected Braille display", e);
+ disconnect();
+ }
+ });
+ }
+ }
+
+ /**
+ * Starts reading HID bytes from this Braille display.
+ *
+ * <p>Reads are performed on a background thread.
+ */
+ private void startReadingLocked() {
+ mInputThread = new Thread(() -> {
+ Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
+ try (InputStream inputStream = new FileInputStream(mHidrawNode)) {
+ final byte[] buffer = new byte[IBinder.getSuggestedMaxIpcSizeBytes()];
+ int readSize;
+ while (!Thread.interrupted()) {
+ if (!mHidrawNode.exists()) {
+ disconnect();
+ break;
+ }
+ // Reading from the HIDRAW character device node will block
+ // until bytes are available.
+ readSize = inputStream.read(buffer);
+ if (readSize > 0) {
+ try {
+ // Send the input to the AccessibilityService.
+ mController.onInput(Arrays.copyOfRange(buffer, 0, readSize));
+ } catch (RemoteException e) {
+ // Error communicating with the AccessibilityService.
+ Slog.e(LOG_TAG, "Error calling onInput", e);
+ disconnect();
+ break;
+ }
+ }
+ }
+ } catch (IOException e) {
+ Slog.d(LOG_TAG, "Error reading from connected Braille display", e);
+ disconnect();
+ }
+ }, "BrailleDisplayConnection input thread");
+ mInputThread.setDaemon(true);
+ mInputThread.start();
+ }
+
+ /** Stop the Input thread. */
+ private void closeInputLocked() {
+ if (mInputThread != null) {
+ mInputThread.interrupt();
+ }
+ mInputThread = null;
+ }
+
+ /** Stop the Output thread and close the Output stream. */
+ private void closeOutputLocked() {
+ if (mOutputThread != null) {
+ mOutputThread.quit();
+ }
+ mOutputThread = null;
+ if (mOutputStream != null) {
+ try {
+ mOutputStream.close();
+ } catch (IOException e) {
+ Slog.e(LOG_TAG, "Unable to close output stream", e);
+ }
+ }
+ mOutputStream = null;
+ }
+
+ /**
+ * Returns a {@link BrailleDisplayScanner} that opens {@link FileInputStream}s to read
+ * from HIDRAW nodes and perform ioctls using the provided {@link NativeInterface}.
+ */
+ @VisibleForTesting
+ BrailleDisplayScanner getDefaultNativeScanner(@NonNull NativeInterface nativeInterface) {
+ Objects.requireNonNull(nativeInterface);
+ return new BrailleDisplayScanner() {
+ private static final Path DEVICE_DIR = Path.of("/dev");
+ private static final String HIDRAW_DEVICE_GLOB = "hidraw*";
+
+ @Override
+ public Collection<Path> getHidrawNodePaths() {
+ final List<Path> result = new ArrayList<>();
+ try (DirectoryStream<Path> hidrawNodePaths = Files.newDirectoryStream(
+ DEVICE_DIR, HIDRAW_DEVICE_GLOB)) {
+ for (Path path : hidrawNodePaths) {
+ result.add(path);
+ }
+ return result;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ private <T> T readFromFileDescriptor(Path path, Function<Integer, T> readFn) {
+ try (FileInputStream stream = new FileInputStream(path.toFile())) {
+ return readFn.apply(stream.getFD().getInt$());
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public byte[] getDeviceReportDescriptor(@NonNull Path path) {
+ Objects.requireNonNull(path);
+ return readFromFileDescriptor(path, fd -> {
+ final int descSize = nativeInterface.getHidrawDescSize(fd);
+ if (descSize > 0) {
+ return nativeInterface.getHidrawDesc(fd, descSize);
+ }
+ return null;
+ });
+ }
+
+ @Override
+ public String getUniqueId(@NonNull Path path) {
+ Objects.requireNonNull(path);
+ return readFromFileDescriptor(path, nativeInterface::getHidrawUniq);
+ }
+
+ @Override
+ public int getDeviceBusType(@NonNull Path path) {
+ Objects.requireNonNull(path);
+ Integer busType = readFromFileDescriptor(path, nativeInterface::getHidrawBusType);
+ return busType != null ? busType : BUS_UNKNOWN;
+ }
+ };
+ }
+
+ /**
+ * Sets test data to be used by CTS tests.
+ *
+ * <p>Replaces the default {@link BrailleDisplayScanner} object for this connection,
+ * and also returns it to allow unit testing this test-only implementation.
+ *
+ * @see BrailleDisplayController#setTestBrailleDisplayData
+ */
+ BrailleDisplayScanner setTestData(@NonNull List<Bundle> brailleDisplays) {
+ Objects.requireNonNull(brailleDisplays);
+ final Map<Path, Bundle> brailleDisplayMap = new ArrayMap<>();
+ for (Bundle brailleDisplay : brailleDisplays) {
+ Path hidrawNodePath = Path.of(brailleDisplay.getString(
+ BrailleDisplayController.TEST_BRAILLE_DISPLAY_HIDRAW_PATH));
+ brailleDisplayMap.put(hidrawNodePath, brailleDisplay);
+ }
+ synchronized (mLock) {
+ mScanner = new BrailleDisplayScanner() {
+ @Override
+ public Collection<Path> getHidrawNodePaths() {
+ return brailleDisplayMap.keySet();
+ }
+
+ @Override
+ public byte[] getDeviceReportDescriptor(@NonNull Path path) {
+ return brailleDisplayMap.get(path).getByteArray(
+ BrailleDisplayController.TEST_BRAILLE_DISPLAY_DESCRIPTOR);
+ }
+
+ @Override
+ public String getUniqueId(@NonNull Path path) {
+ return brailleDisplayMap.get(path).getString(
+ BrailleDisplayController.TEST_BRAILLE_DISPLAY_UNIQUE_ID);
+ }
+
+ @Override
+ public int getDeviceBusType(@NonNull Path path) {
+ return brailleDisplayMap.get(path).getBoolean(
+ BrailleDisplayController.TEST_BRAILLE_DISPLAY_BUS_BLUETOOTH)
+ ? BUS_BLUETOOTH : BUS_USB;
+ }
+ };
+ return mScanner;
+ }
+ }
+
+ /**
+ * This interface exists to support unit testing {@link #getDefaultNativeScanner}.
+ */
+ @VisibleForTesting
+ interface NativeInterface {
+ int getHidrawDescSize(int fd);
+
+ byte[] getHidrawDesc(int fd, int descSize);
+
+ String getHidrawUniq(int fd);
+
+ int getHidrawBusType(int fd);
+ }
+
+ /** Native interface that actually calls native HIDRAW ioctls. */
+ private NativeInterface getDefaultNativeInterface() {
+ return new NativeInterface() {
+ @Override
+ public int getHidrawDescSize(int fd) {
+ return nativeGetHidrawDescSize(fd);
+ }
+
+ @Override
+ public byte[] getHidrawDesc(int fd, int descSize) {
+ return nativeGetHidrawDesc(fd, descSize);
+ }
+
+ @Override
+ public String getHidrawUniq(int fd) {
+ return nativeGetHidrawUniq(fd);
+ }
+
+ @Override
+ public int getHidrawBusType(int fd) {
+ return nativeGetHidrawBusType(fd);
+ }
+ };
+ }
+
+ private native int nativeGetHidrawDescSize(int fd);
+
+ private native byte[] nativeGetHidrawDesc(int fd, int descSize);
+
+ private native String nativeGetHidrawUniq(int fd);
+
+ private native int nativeGetHidrawBusType(int fd);
+}
diff --git a/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java b/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java
index 2c50389..df4e699 100644
--- a/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java
+++ b/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java
@@ -35,6 +35,7 @@
import android.content.pm.ParceledListSlice;
import android.os.Binder;
import android.os.IBinder;
+import android.os.IRemoteCallback;
import android.os.Process;
import android.os.ResultReceiver;
import android.os.ShellCallback;
@@ -162,6 +163,13 @@
(service) -> service.onDestroyPredictionSessionLocked(sessionId));
}
+ @Override
+ public void requestServiceFeatures(@NonNull AppPredictionSessionId sessionId,
+ IRemoteCallback callback) {
+ runForUserLocked("requestServiceFeatures", sessionId,
+ (service) -> service.requestServiceFeaturesLocked(sessionId, callback));
+ }
+
public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
@Nullable FileDescriptor err,
@NonNull String[] args, @Nullable ShellCallback callback,
diff --git a/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java b/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
index 84707a8..a0198f2 100644
--- a/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
+++ b/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
@@ -31,6 +31,7 @@
import android.content.pm.ParceledListSlice;
import android.content.pm.ServiceInfo;
import android.os.IBinder;
+import android.os.IRemoteCallback;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.provider.DeviceConfig;
@@ -237,6 +238,18 @@
sessionInfo.destroy();
}
+ /**
+ * Requests the service to provide AppPredictionService features info.
+ */
+ @GuardedBy("mLock")
+ public void requestServiceFeaturesLocked(@NonNull AppPredictionSessionId sessionId,
+ @NonNull IRemoteCallback callback) {
+ final AppPredictionSessionInfo sessionInfo = mSessionInfos.get(sessionId);
+ if (sessionInfo == null) return;
+ resolveService(sessionId, true, sessionInfo.mUsesPeopleService,
+ s -> s.requestServiceFeatures(sessionId, callback));
+ }
+
@Override
public void onFailureOrTimeout(boolean timedOut) {
if (isDebug()) {
diff --git a/services/core/java/com/android/server/SystemConfig.java b/services/core/java/com/android/server/SystemConfig.java
index 2e14abb..a341b4a 100644
--- a/services/core/java/com/android/server/SystemConfig.java
+++ b/services/core/java/com/android/server/SystemConfig.java
@@ -263,10 +263,6 @@
// location settings are off, for emergency purposes, as read from the configuration files.
final ArrayMap<String, ArraySet<String>> mAllowIgnoreLocationSettings = new ArrayMap<>();
- // These are the packages that are allow-listed to be able to access camera when
- // the camera privacy state is for driver assistance apps only.
- final ArrayMap<String, Boolean> mAllowlistCameraPrivacy = new ArrayMap<>();
-
// These are the action strings of broadcasts which are whitelisted to
// be delivered anonymously even to apps which target O+.
final ArraySet<String> mAllowImplicitBroadcasts = new ArraySet<>();
@@ -487,10 +483,6 @@
return mAllowedAssociations;
}
- public ArrayMap<String, Boolean> getCameraPrivacyAllowlist() {
- return mAllowlistCameraPrivacy;
- }
-
public ArraySet<String> getBugreportWhitelistedPackages() {
return mBugreportWhitelistedPackages;
}
@@ -1070,22 +1062,6 @@
}
XmlUtils.skipCurrentTag(parser);
} break;
- case "camera-privacy-allowlisted-app" : {
- if (allowOverrideAppRestrictions) {
- String pkgname = parser.getAttributeValue(null, "package");
- boolean isMandatory = XmlUtils.readBooleanAttribute(
- parser, "mandatory", false);
- if (pkgname == null) {
- Slog.w(TAG, "<" + name + "> without package in "
- + permFile + " at " + parser.getPositionDescription());
- } else {
- mAllowlistCameraPrivacy.put(pkgname, isMandatory);
- }
- } else {
- logNotAllowedInPartition(name, permFile, parser);
- }
- XmlUtils.skipCurrentTag(parser);
- } break;
case "allow-ignore-location-settings": {
if (allowOverrideAppRestrictions) {
String pkgname = parser.getAttributeValue(null, "package");
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index cd45b03..b8f6b3f 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -480,9 +480,14 @@
/**
* The available ANR timers.
*/
+ // ActivityManagerConstants.SERVICE_TIMEOUT/ActivityManagerConstants.SERVICE_BACKGROUND_TIMEOUT
private final ProcessAnrTimer mActiveServiceAnrTimer;
+ // see ServiceRecord$ShortFgsInfo#getAnrTime()
private final ServiceAnrTimer mShortFGSAnrTimer;
+ // ActivityManagerConstants.DEFAULT_SERVICE_START_FOREGROUND_TIMEOUT_MS
private final ServiceAnrTimer mServiceFGAnrTimer;
+ // see ServiceRecord#getEarliestStopTypeAndTime()
+ private final ServiceAnrTimer mFGSAnrTimer;
// allowlisted packageName.
ArraySet<String> mAllowListWhileInUsePermissionInFgs = new ArraySet<>();
@@ -744,10 +749,13 @@
"SERVICE_TIMEOUT");
this.mShortFGSAnrTimer = new ServiceAnrTimer(service,
ActivityManagerService.SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG,
- "FGS_TIMEOUT");
+ "SHORT_FGS_TIMEOUT");
this.mServiceFGAnrTimer = new ServiceAnrTimer(service,
ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG,
"SERVICE_FOREGROUND_TIMEOUT");
+ this.mFGSAnrTimer = new ServiceAnrTimer(service,
+ ActivityManagerService.SERVICE_FGS_ANR_TIMEOUT_MSG,
+ "FGS_TIMEOUT");
}
void systemServicesReady() {
@@ -1570,6 +1578,7 @@
}
maybeStopShortFgsTimeoutLocked(service);
+ maybeStopFgsTimeoutLocked(service);
final int uid = service.appInfo.uid;
final String packageName = service.name.getPackageName();
@@ -1758,6 +1767,7 @@
}
maybeStopShortFgsTimeoutLocked(r);
+ maybeStopFgsTimeoutLocked(r);
final int uid = r.appInfo.uid;
final String packageName = r.name.getPackageName();
@@ -2243,6 +2253,8 @@
// Whether to extend the SHORT_SERVICE time out.
boolean extendShortServiceTimeout = false;
+ // Whether to extend the timeout for a time-limited FGS type.
+ boolean extendFgsTimeout = false;
// Whether setFgsRestrictionLocked() is called in here. Only used for logging.
boolean fgsRestrictionRecalculated = false;
@@ -2287,6 +2299,19 @@
final boolean isOldTypeShortFgsAndTimedOut =
r.shouldTriggerShortFgsTimeout(nowUptime);
+ // Calling startForeground on a FGS type which has a time limit will only be
+ // allowed if the app is in a state where it can normally start another FGS.
+ // The timeout will behave as follows:
+ // A) <TIME_LIMITED_TYPE> -> another <TIME_LIMITED_TYPE>
+ // - If the start succeeds, the timeout is reset.
+ // B) <TIME_LIMITED_TYPE> -> non-time-limited type
+ // - If the start succeeds, the timeout will stop.
+ // C) non-time-limited type -> <TIME_LIMITED_TYPE>
+ // - If the start succeeds, the timeout will start.
+ final boolean isOldTypeTimeLimited = r.isFgsTimeLimited();
+ final boolean isNewTypeTimeLimited =
+ r.canFgsTypeTimeOut(foregroundServiceType);
+
// If true, we skip the BFSL check.
boolean bypassBfslCheck = false;
@@ -2355,6 +2380,35 @@
// "if (r.mAllowStartForeground == REASON_DENIED...)" block below.
}
}
+ } else if (r.isForeground && isOldTypeTimeLimited) {
+
+ // See if the app could start an FGS or not.
+ r.clearFgsAllowStart();
+ setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
+ r.appInfo.uid, r.intent.getIntent(), r, r.userId,
+ BackgroundStartPrivileges.NONE, false /* isBindService */);
+ fgsRestrictionRecalculated = true;
+
+ final boolean fgsStartAllowed = !isBgFgsRestrictionEnabledForService
+ || r.isFgsAllowedStart();
+
+ if (fgsStartAllowed) {
+ if (isNewTypeTimeLimited) {
+ // Note: in the future, we may want to look into metrics to see if
+ // apps are constantly switching between a time-limited type and a
+ // non-time-limited type or constantly calling startForeground()
+ // opportunistically on the same type to gain runtime and apply the
+ // stricter timeout. For now, always extend the timeout if the app
+ // is in a state where it's allowed to start a FGS.
+ extendFgsTimeout = true;
+ } else {
+ // FGS type is changing from a time-restricted type to one without
+ // a time limit so proceed as normal.
+ // The timeout will stop later, in maybeUpdateFgsTrackingLocked().
+ }
+ } else {
+ // This case will be handled in the BFSL check below.
+ }
} else if (r.mStartForegroundCount == 0) {
/*
If the service was started with startService(), not
@@ -2596,6 +2650,7 @@
maybeUpdateShortFgsTrackingLocked(r,
extendShortServiceTimeout);
+ maybeUpdateFgsTrackingLocked(r, extendFgsTimeout);
} else {
if (DEBUG_FOREGROUND_SERVICE) {
Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
@@ -2631,6 +2686,7 @@
}
maybeStopShortFgsTimeoutLocked(r);
+ maybeStopFgsTimeoutLocked(r);
// Adjust notification handling before setting isForeground to false, because
// that state is relevant to the notification policy side.
@@ -3608,6 +3664,116 @@
}
}
+ void onFgsTimeout(ServiceRecord sr) {
+ synchronized (mAm) {
+ final long nowUptime = SystemClock.uptimeMillis();
+ final int fgsType = sr.getTimedOutFgsType(nowUptime);
+ if (fgsType == -1) {
+ mFGSAnrTimer.discard(sr);
+ return;
+ }
+ Slog.e(TAG_SERVICE, "FGS (" + ServiceInfo.foregroundServiceTypeToLabel(fgsType)
+ + ") timed out: " + sr);
+ mFGSAnrTimer.accept(sr);
+ traceInstant("FGS timed out: ", sr);
+
+ logFGSStateChangeLocked(sr,
+ FOREGROUND_SERVICE_STATE_CHANGED__STATE__TIMED_OUT,
+ nowUptime > sr.mFgsEnterTime ? (int) (nowUptime - sr.mFgsEnterTime) : 0,
+ FGS_STOP_REASON_UNKNOWN,
+ FGS_TYPE_POLICY_CHECK_UNKNOWN,
+ FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
+ false /* fgsRestrictionRecalculated */
+ );
+ try {
+ sr.app.getThread().scheduleTimeoutServiceForType(sr, sr.getLastStartId(), fgsType);
+ } catch (RemoteException e) {
+ Slog.w(TAG_SERVICE, "Exception from scheduleTimeoutServiceForType: " + e);
+ }
+
+ // ANR the service after giving the service some time to clean up.
+ // ServiceRecord.getEarliestStopTypeAndTime() is an absolute time with a reference that
+ // is not "now". Compute the time from "now" when starting the anr timer.
+ final long anrTime = sr.getEarliestStopTypeAndTime().second
+ + mAm.mConstants.mFgsAnrExtraWaitDuration - SystemClock.uptimeMillis();
+ mFGSAnrTimer.start(sr, anrTime);
+ }
+ }
+
+ private void maybeUpdateFgsTrackingLocked(ServiceRecord sr, boolean extendTimeout) {
+ if (!sr.isFgsTimeLimited()) {
+ // Reset timers if they exist.
+ sr.setIsFgsTimeLimited(false);
+ mFGSAnrTimer.cancel(sr);
+ mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
+ return;
+ }
+
+ if (extendTimeout || !sr.wasFgsPreviouslyTimeLimited()) {
+ traceInstant("FGS start: ", sr);
+ sr.setIsFgsTimeLimited(true);
+
+ // We'll restart the timeout.
+ mFGSAnrTimer.cancel(sr);
+ mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
+
+ final Message msg = mAm.mHandler.obtainMessage(
+ ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
+ mAm.mHandler.sendMessageAtTime(msg, sr.getEarliestStopTypeAndTime().second);
+ }
+ }
+
+ private void maybeStopFgsTimeoutLocked(ServiceRecord sr) {
+ sr.setIsFgsTimeLimited(false); // reset fgs boolean holding time-limited type state.
+ if (!sr.isFgsTimeLimited()) {
+ return; // if none of the types are time-limited, return.
+ }
+ Slog.d(TAG_SERVICE, "Stop FGS timeout: " + sr);
+ mFGSAnrTimer.cancel(sr);
+ mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
+ }
+
+ boolean hasServiceTimedOutLocked(ComponentName className, IBinder token) {
+ final int userId = UserHandle.getCallingUserId();
+ final long ident = mAm.mInjector.clearCallingIdentity();
+ try {
+ ServiceRecord sr = findServiceLocked(className, token, userId);
+ if (sr == null) {
+ return false;
+ }
+ final long nowUptime = SystemClock.uptimeMillis();
+ return sr.getTimedOutFgsType(nowUptime) != -1;
+ } finally {
+ mAm.mInjector.restoreCallingIdentity(ident);
+ }
+ }
+
+ void onFgsAnrTimeout(ServiceRecord sr) {
+ final long nowUptime = SystemClock.uptimeMillis();
+ final int fgsType = sr.getTimedOutFgsType(nowUptime);
+ if (fgsType == -1 || !sr.wasFgsPreviouslyTimeLimited()) {
+ return; // no timed out FGS type was found
+ }
+ final String reason = "A foreground service of type "
+ + ServiceInfo.foregroundServiceTypeToLabel(fgsType)
+ + " did not stop within a timeout: " + sr.getComponentName();
+
+ final TimeoutRecord tr = TimeoutRecord.forFgsTimeout(reason);
+
+ tr.mLatencyTracker.waitingOnAMSLockStarted();
+ synchronized (mAm) {
+ tr.mLatencyTracker.waitingOnAMSLockEnded();
+
+ Slog.e(TAG_SERVICE, "FGS ANR'ed: " + sr);
+ traceInstant("FGS ANR: ", sr);
+ mAm.appNotResponding(sr.app, tr);
+
+ // TODO: Can we close the ANR dialog here, if it's still shown? Currently, the ANR
+ // dialog really doesn't remember the "cause" (especially if there have been multiple
+ // ANRs), so it's not doable.
+ }
+ }
+
private void updateAllowlistManagerLocked(ProcessServiceRecord psr) {
psr.mAllowlistManager = false;
for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
@@ -3621,6 +3787,7 @@
private void stopServiceAndUpdateAllowlistManagerLocked(ServiceRecord service) {
maybeStopShortFgsTimeoutLocked(service);
+ maybeStopFgsTimeoutLocked(service);
final ProcessServiceRecord psr = service.app.mServices;
psr.stopService(service);
psr.updateBoundClientUids();
@@ -5893,6 +6060,7 @@
Slog.w(TAG_SERVICE, "Short FGS brought down without stopping: " + r);
maybeStopShortFgsTimeoutLocked(r);
}
+ maybeStopFgsTimeoutLocked(r);
// Report to all of the connections that the service is no longer
// available.
@@ -6015,6 +6183,7 @@
final boolean exitingFg = r.isForeground;
if (exitingFg) {
maybeStopShortFgsTimeoutLocked(r);
+ maybeStopFgsTimeoutLocked(r);
decActiveForegroundAppLocked(smap, r);
synchronized (mAm.mProcessStats.mLock) {
ServiceState stracker = r.getTracker();
@@ -8643,7 +8812,7 @@
event = EventLogTags.AM_FOREGROUND_SERVICE_DENIED;
} else if (state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__TIMED_OUT) {
event = EventLogTags.AM_FOREGROUND_SERVICE_TIMED_OUT;
- }else {
+ } else {
// Unknown event.
return;
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java
index 72e62c3..d97731c 100644
--- a/services/core/java/com/android/server/am/ActivityManagerConstants.java
+++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java
@@ -1052,6 +1052,27 @@
public volatile long mShortFgsProcStateExtraWaitDuration =
DEFAULT_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION;
+ /** Timeout for a mediaProcessing FGS, in milliseconds. */
+ private static final String KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION =
+ "media_processing_fgs_timeout_duration";
+
+ /** @see #KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION */
+ static final long DEFAULT_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION = 6 * 60 * 60_000; // 6 hours
+
+ /** @see #KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION */
+ public volatile long mMediaProcessingFgsTimeoutDuration =
+ DEFAULT_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION;
+
+ /** Timeout for a dataSync FGS, in milliseconds. */
+ private static final String KEY_DATA_SYNC_FGS_TIMEOUT_DURATION =
+ "data_sync_fgs_timeout_duration";
+
+ /** @see #KEY_DATA_SYNC_FGS_TIMEOUT_DURATION */
+ static final long DEFAULT_DATA_SYNC_FGS_TIMEOUT_DURATION = 6 * 60 * 60_000; // 6 hours
+
+ /** @see #KEY_DATA_SYNC_FGS_TIMEOUT_DURATION */
+ public volatile long mDataSyncFgsTimeoutDuration = DEFAULT_DATA_SYNC_FGS_TIMEOUT_DURATION;
+
/**
* If enabled, when starting an application, the system will wait for a
* {@link ActivityManagerService#finishAttachApplication} from the app before scheduling
@@ -1082,6 +1103,20 @@
public volatile long mShortFgsAnrExtraWaitDuration =
DEFAULT_SHORT_FGS_ANR_EXTRA_WAIT_DURATION;
+ /**
+ * If a service of a timeout-enforced type doesn't finish within this duration after its
+ * timeout, then we'll declare an ANR.
+ * i.e. if the time limit for a type is 1 hour, and this extra duration is 10 seconds, then
+ * the app will be ANR'ed 1 hour and 10 seconds after it started.
+ */
+ private static final String KEY_FGS_ANR_EXTRA_WAIT_DURATION = "fgs_anr_extra_wait_duration";
+
+ /** @see #KEY_FGS_ANR_EXTRA_WAIT_DURATION */
+ static final long DEFAULT_FGS_ANR_EXTRA_WAIT_DURATION = 10_000;
+
+ /** @see #KEY_FGS_ANR_EXTRA_WAIT_DURATION */
+ public volatile long mFgsAnrExtraWaitDuration = DEFAULT_FGS_ANR_EXTRA_WAIT_DURATION;
+
/** @see #KEY_USE_TIERED_CACHED_ADJ */
public boolean USE_TIERED_CACHED_ADJ = DEFAULT_USE_TIERED_CACHED_ADJ;
@@ -1264,9 +1299,18 @@
case KEY_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION:
updateShortFgsProcStateExtraWaitDuration();
break;
+ case KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION:
+ updateMediaProcessingFgsTimeoutDuration();
+ break;
+ case KEY_DATA_SYNC_FGS_TIMEOUT_DURATION:
+ updateDataSyncFgsTimeoutDuration();
+ break;
case KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION:
updateShortFgsAnrExtraWaitDuration();
break;
+ case KEY_FGS_ANR_EXTRA_WAIT_DURATION:
+ updateFgsAnrExtraWaitDuration();
+ break;
case KEY_PROACTIVE_KILLS_ENABLED:
updateProactiveKillsEnabled();
break;
@@ -2064,6 +2108,27 @@
DEFAULT_SHORT_FGS_ANR_EXTRA_WAIT_DURATION);
}
+ private void updateMediaProcessingFgsTimeoutDuration() {
+ mMediaProcessingFgsTimeoutDuration = DeviceConfig.getLong(
+ DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+ KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION,
+ DEFAULT_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION);
+ }
+
+ private void updateDataSyncFgsTimeoutDuration() {
+ mDataSyncFgsTimeoutDuration = DeviceConfig.getLong(
+ DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+ KEY_DATA_SYNC_FGS_TIMEOUT_DURATION,
+ DEFAULT_DATA_SYNC_FGS_TIMEOUT_DURATION);
+ }
+
+ private void updateFgsAnrExtraWaitDuration() {
+ mFgsAnrExtraWaitDuration = DeviceConfig.getLong(
+ DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+ KEY_FGS_ANR_EXTRA_WAIT_DURATION,
+ DEFAULT_FGS_ANR_EXTRA_WAIT_DURATION);
+ }
+
private void updateEnableWaitForFinishAttachApplication() {
mEnableWaitForFinishAttachApplication = DeviceConfig.getBoolean(
DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
@@ -2295,6 +2360,13 @@
pw.print(" "); pw.print(KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION);
pw.print("="); pw.println(mShortFgsAnrExtraWaitDuration);
+ pw.print(" "); pw.print(KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION);
+ pw.print("="); pw.println(mMediaProcessingFgsTimeoutDuration);
+ pw.print(" "); pw.print(KEY_DATA_SYNC_FGS_TIMEOUT_DURATION);
+ pw.print("="); pw.println(mDataSyncFgsTimeoutDuration);
+ pw.print(" "); pw.print(KEY_FGS_ANR_EXTRA_WAIT_DURATION);
+ pw.print("="); pw.println(mFgsAnrExtraWaitDuration);
+
pw.print(" "); pw.print(KEY_USE_TIERED_CACHED_ADJ);
pw.print("="); pw.println(USE_TIERED_CACHED_ADJ);
pw.print(" "); pw.print(KEY_TIERED_CACHED_ADJ_DECAY_TIME);
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 2750344..bfdcb95 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -1702,6 +1702,8 @@
static final int REMOVE_UID_FROM_OBSERVER_MSG = 81;
static final int BIND_APPLICATION_TIMEOUT_SOFT_MSG = 82;
static final int BIND_APPLICATION_TIMEOUT_HARD_MSG = 83;
+ static final int SERVICE_FGS_TIMEOUT_MSG = 84;
+ static final int SERVICE_FGS_ANR_TIMEOUT_MSG = 85;
static final int FIRST_BROADCAST_QUEUE_MSG = 200;
@@ -2064,6 +2066,12 @@
case BIND_APPLICATION_TIMEOUT_HARD_MSG: {
handleBindApplicationTimeoutHard((ProcessRecord) msg.obj);
} break;
+ case SERVICE_FGS_TIMEOUT_MSG: {
+ mServices.onFgsTimeout((ServiceRecord) msg.obj);
+ } break;
+ case SERVICE_FGS_ANR_TIMEOUT_MSG: {
+ mServices.onFgsAnrTimeout((ServiceRecord) msg.obj);
+ } break;
}
}
}
@@ -13794,6 +13802,13 @@
}
@Override
+ public boolean hasServiceTimeLimitExceeded(ComponentName className, IBinder token) {
+ synchronized (this) {
+ return mServices.hasServiceTimedOutLocked(className, token);
+ }
+ }
+
+ @Override
public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
boolean requireFull, String name, String callerPackage) {
return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java
index 2771572..3c8d7fc 100644
--- a/services/core/java/com/android/server/am/ServiceRecord.java
+++ b/services/core/java/com/android/server/am/ServiceRecord.java
@@ -56,6 +56,7 @@
import android.os.UserHandle;
import android.provider.Settings;
import android.util.ArrayMap;
+import android.util.Pair;
import android.util.Slog;
import android.util.TimeUtils;
import android.util.proto.ProtoOutputStream;
@@ -236,6 +237,8 @@
boolean mFgsNotificationShown;
// Whether FGS package has permissions to show notifications.
boolean mFgsHasNotificationPermission;
+ // Whether the FGS contains a type that is time limited.
+ private boolean mFgsIsTimeLimited;
// allow the service becomes foreground service? Service started from background may not be
// allowed to become a foreground service.
@@ -915,6 +918,7 @@
pw.print(prefix); pw.print("isForeground="); pw.print(isForeground);
pw.print(" foregroundId="); pw.print(foregroundId);
pw.printf(" types=%08X", foregroundServiceType);
+ pw.print(" fgsHasTimeLimitedType="); pw.print(mFgsIsTimeLimited);
pw.print(" foregroundNoti="); pw.println(foregroundNoti);
if (isShortFgs() && mShortFgsInfo != null) {
@@ -1789,6 +1793,83 @@
+ " " + (mShortFgsInfo == null ? "" : mShortFgsInfo.getDescription());
}
+ /**
+ * @return true if one of the types of this FGS has a time limit.
+ */
+ public boolean isFgsTimeLimited() {
+ return startRequested && isForeground && canFgsTypeTimeOut(foregroundServiceType);
+ }
+
+ /**
+ * Called when a FGS with a time-limited type starts ({@code true}) or stops ({@code false}).
+ */
+ public void setIsFgsTimeLimited(boolean fgsIsTimeLimited) {
+ this.mFgsIsTimeLimited = fgsIsTimeLimited;
+ }
+
+ /**
+ * @return whether {@link #mFgsIsTimeLimited} was previously set or not.
+ */
+ public boolean wasFgsPreviouslyTimeLimited() {
+ return mFgsIsTimeLimited;
+ }
+
+ /**
+ * @return the FGS type if the service has reached its time limit, otherwise -1.
+ */
+ public int getTimedOutFgsType(long nowUptime) {
+ if (!isAppAlive() || !isFgsTimeLimited()) {
+ return -1;
+ }
+
+ final Pair<Integer, Long> fgsTypeAndStopTime = getEarliestStopTypeAndTime();
+ if (fgsTypeAndStopTime.first != -1 && fgsTypeAndStopTime.second <= nowUptime) {
+ return fgsTypeAndStopTime.first;
+ }
+ return -1; // no fgs type exceeded time limit
+ }
+
+ /**
+ * @return a {@code Pair<fgs_type, stop_time>}, representing the earliest time at which the FGS
+ * should be stopped (fgs start time + time limit for most restrictive type)
+ */
+ Pair<Integer, Long> getEarliestStopTypeAndTime() {
+ int fgsType = -1;
+ long timeout = 0;
+ if ((foregroundServiceType & ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING)
+ == ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING) {
+ fgsType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING;
+ timeout = ams.mConstants.mMediaProcessingFgsTimeoutDuration;
+ }
+ if ((foregroundServiceType & ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
+ == ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) {
+ // update the timeout and type if this type has a more restrictive time limit
+ if (timeout == 0 || ams.mConstants.mDataSyncFgsTimeoutDuration < timeout) {
+ fgsType = ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC;
+ timeout = ams.mConstants.mDataSyncFgsTimeoutDuration;
+ }
+ }
+ // Add the logic for time limits introduced in the future for other fgs types here.
+ return Pair.create(fgsType, timeout == 0 ? 0 : (mFgsEnterTime + timeout));
+ }
+
+ /**
+ * Check if the given types contain a type which is time restricted.
+ */
+ boolean canFgsTypeTimeOut(int fgsType) {
+ // The below conditionals are not simplified on purpose to help with readability.
+ if ((fgsType & ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING)
+ == ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING) {
+ return true;
+ }
+ if ((fgsType & ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
+ == ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) {
+ return true;
+ }
+ // Additional types which have time limits should be added here in the future.
+ return false;
+ }
+
private boolean isAppAlive() {
if (app == null) {
return false;
diff --git a/services/core/java/com/android/server/am/TEST_MAPPING b/services/core/java/com/android/server/am/TEST_MAPPING
index bd3c8e0..feab2c05 100644
--- a/services/core/java/com/android/server/am/TEST_MAPPING
+++ b/services/core/java/com/android/server/am/TEST_MAPPING
@@ -157,7 +157,6 @@
]
},
{
- "file_patterns": ["Broadcast.*"],
"name": "CtsContentTestCases",
"options": [
{ "include-filter": "android.content.cts.BroadcastReceiverTest" },
diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java
index 96c6be8..55ac4cf 100644
--- a/services/core/java/com/android/server/am/UserController.java
+++ b/services/core/java/com/android/server/am/UserController.java
@@ -1350,41 +1350,57 @@
}
/**
- * For mDelayUserDataLocking mode, storage once unlocked is kept unlocked.
- * Total number of unlocked user storage is limited by mMaxRunningUsers.
- * If there are more unlocked users, evict and lock the least recently stopped user and
- * lock that user's data. Regardless of the mode, ephemeral user is always locked
- * immediately.
+ * Returns which user, if any, should be locked when the given user is stopped.
+ *
+ * For typical (non-mDelayUserDataLocking) devices and users, this will be the provided user.
+ *
+ * However, for some devices or users (based on {@link #canDelayDataLockingForUser(int)}),
+ * storage once unlocked is kept unlocked, even after the user is stopped, so the user to be
+ * locked (if any) may differ.
+ *
+ * For mDelayUserDataLocking devices, the total number of unlocked user storage is limited
+ * (currently by mMaxRunningUsers). If there are more unlocked users, evict and lock the least
+ * recently stopped user and lock that user's data.
+ *
+ * Regardless of the mode, ephemeral user is always locked immediately.
*
* @return user id to lock. UserHandler.USER_NULL will be returned if no user should be locked.
*/
@GuardedBy("mLock")
private int updateUserToLockLU(@UserIdInt int userId, boolean allowDelayedLocking) {
- int userIdToLock = userId;
- // TODO: Decouple the delayed locking flows from mMaxRunningUsers or rename the property to
- // state maximum running unlocked users specifically
- if (canDelayDataLockingForUser(userIdToLock) && allowDelayedLocking
- && !getUserInfo(userId).isEphemeral()
- && !hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, userId)) {
+ if (!canDelayDataLockingForUser(userId)
+ || !allowDelayedLocking
+ || getUserInfo(userId).isEphemeral()
+ || hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, userId)) {
+ return userId;
+ }
+
+ // Once we reach here, we are in a delayed locking scenario.
+ // Now, no user will be locked, unless the device's policy dictates we should based on the
+ // maximum of such users allowed for the device.
+ if (mDelayUserDataLocking) {
// arg should be object, not index
mLastActiveUsersForDelayedLocking.remove((Integer) userId);
mLastActiveUsersForDelayedLocking.add(0, userId);
int totalUnlockedUsers = mStartedUsers.size()
+ mLastActiveUsersForDelayedLocking.size();
+ // TODO: Decouple the delayed locking flows from mMaxRunningUsers. These users aren't
+ // running so this calculation shouldn't be based on this parameter. Also note that
+ // that if these devices ever support background running users (such as profiles), the
+ // implementation is incorrect since starting such users can cause the max to be
+ // exceeded.
if (totalUnlockedUsers > mMaxRunningUsers) { // should lock a user
- userIdToLock = mLastActiveUsersForDelayedLocking.get(
+ final int userIdToLock = mLastActiveUsersForDelayedLocking.get(
mLastActiveUsersForDelayedLocking.size() - 1);
mLastActiveUsersForDelayedLocking
.remove(mLastActiveUsersForDelayedLocking.size() - 1);
- Slogf.i(TAG, "finishUserStopped, stopping user:" + userId
- + " lock user:" + userIdToLock);
- } else {
- Slogf.i(TAG, "finishUserStopped, user:" + userId + ", skip locking");
- // do not lock
- userIdToLock = UserHandle.USER_NULL;
+ Slogf.i(TAG, "finishUserStopped: should stop user " + userId
+ + " but should lock user " + userIdToLock);
+ return userIdToLock;
}
}
- return userIdToLock;
+ Slogf.i(TAG, "finishUserStopped: should stop user " + userId + " but without any locking");
+ return UserHandle.USER_NULL;
}
/**
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 63ea7b4..5c95d43 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -106,7 +106,6 @@
import android.content.pm.PermissionInfo;
import android.content.pm.UserInfo;
import android.database.ContentObserver;
-import android.hardware.SensorPrivacyManager;
import android.hardware.camera2.CameraDevice.CAMERA_AUDIO_RESTRICTION;
import android.net.Uri;
import android.os.AsyncTask;
@@ -152,7 +151,6 @@
import com.android.internal.app.IAppOpsService;
import com.android.internal.app.IAppOpsStartedCallback;
import com.android.internal.app.MessageSamplingConfig;
-import com.android.internal.camera.flags.Flags;
import com.android.internal.compat.IPlatformCompat;
import com.android.internal.os.Clock;
import com.android.internal.pm.pkg.component.ParsedAttribution;
@@ -225,8 +223,6 @@
*/
private static final int CURRENT_VERSION = 1;
- private SensorPrivacyManager mSensorPrivacyManager;
-
// Write at most every 30 minutes.
static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
@@ -1235,7 +1231,6 @@
}
}
});
- mSensorPrivacyManager = SensorPrivacyManager.getInstance(mContext);
}
@VisibleForTesting
@@ -4647,10 +4642,6 @@
return pmi.isPackageSuspended(packageName, UserHandle.getUserId(uid));
}
- private boolean isAutomotive() {
- return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
- }
-
private boolean isOpRestrictedLocked(int uid, int code, String packageName,
String attributionTag, int virtualDeviceId, @Nullable RestrictionBypass appBypass,
boolean isCheckOp) {
@@ -4667,14 +4658,6 @@
}
}
- if (Flags.privacyAllowlist()) {
- if ((code == OP_CAMERA) && isAutomotive()) {
- if (mSensorPrivacyManager.isCameraPrivacyEnabled(packageName)) {
- return true;
- }
- }
- }
-
int userHandle = UserHandle.getUserId(uid);
restrictionSetCount = mOpUserRestrictions.size();
diff --git a/services/core/java/com/android/server/devicestate/DeviceStateManagerService.java b/services/core/java/com/android/server/devicestate/DeviceStateManagerService.java
index cb15abc..cd064ae 100644
--- a/services/core/java/com/android/server/devicestate/DeviceStateManagerService.java
+++ b/services/core/java/com/android/server/devicestate/DeviceStateManagerService.java
@@ -19,11 +19,11 @@
import static android.Manifest.permission.CONTROL_DEVICE_STATE;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
+import static android.hardware.devicestate.DeviceState.FLAG_CANCEL_OVERRIDE_REQUESTS;
import static android.hardware.devicestate.DeviceStateManager.INVALID_DEVICE_STATE;
import static android.hardware.devicestate.DeviceStateManager.MAXIMUM_DEVICE_STATE;
import static android.hardware.devicestate.DeviceStateManager.MINIMUM_DEVICE_STATE;
-import static com.android.server.devicestate.DeviceState.FLAG_CANCEL_OVERRIDE_REQUESTS;
import static com.android.server.devicestate.OverrideRequest.OVERRIDE_REQUEST_TYPE_BASE_STATE;
import static com.android.server.devicestate.OverrideRequest.OVERRIDE_REQUEST_TYPE_EMULATED_STATE;
import static com.android.server.devicestate.OverrideRequestController.FLAG_POWER_SAVE_ENABLED;
@@ -40,6 +40,7 @@
import android.app.ActivityManagerInternal;
import android.app.IProcessObserver;
import android.content.Context;
+import android.hardware.devicestate.DeviceState;
import android.hardware.devicestate.DeviceStateInfo;
import android.hardware.devicestate.DeviceStateManager;
import android.hardware.devicestate.DeviceStateManagerInternal;
diff --git a/services/core/java/com/android/server/devicestate/DeviceStateManagerShellCommand.java b/services/core/java/com/android/server/devicestate/DeviceStateManagerShellCommand.java
index 8c6068d..02c9bb3 100644
--- a/services/core/java/com/android/server/devicestate/DeviceStateManagerShellCommand.java
+++ b/services/core/java/com/android/server/devicestate/DeviceStateManagerShellCommand.java
@@ -18,6 +18,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.hardware.devicestate.DeviceState;
import android.hardware.devicestate.DeviceStateManager;
import android.hardware.devicestate.DeviceStateRequest;
import android.os.Binder;
diff --git a/services/core/java/com/android/server/devicestate/DeviceStateProvider.java b/services/core/java/com/android/server/devicestate/DeviceStateProvider.java
index d5945f4..65b393a 100644
--- a/services/core/java/com/android/server/devicestate/DeviceStateProvider.java
+++ b/services/core/java/com/android/server/devicestate/DeviceStateProvider.java
@@ -21,6 +21,7 @@
import android.annotation.IntDef;
import android.annotation.IntRange;
+import android.hardware.devicestate.DeviceState;
import android.util.Dumpable;
import java.lang.annotation.Retention;
diff --git a/services/core/java/com/android/server/devicestate/OverrideRequest.java b/services/core/java/com/android/server/devicestate/OverrideRequest.java
index 20485c1..d92629f 100644
--- a/services/core/java/com/android/server/devicestate/OverrideRequest.java
+++ b/services/core/java/com/android/server/devicestate/OverrideRequest.java
@@ -18,6 +18,7 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.hardware.devicestate.DeviceState;
import android.hardware.devicestate.DeviceStateRequest;
import android.os.IBinder;
diff --git a/services/core/java/com/android/server/devicestate/OverrideRequestController.java b/services/core/java/com/android/server/devicestate/OverrideRequestController.java
index f5f2fa8..6c3fd83d 100644
--- a/services/core/java/com/android/server/devicestate/OverrideRequestController.java
+++ b/services/core/java/com/android/server/devicestate/OverrideRequestController.java
@@ -18,6 +18,7 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.hardware.devicestate.DeviceState;
import android.hardware.devicestate.DeviceStateRequest;
import android.os.IBinder;
import android.util.Slog;
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index b8a63cd..96c0c8a 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -3560,8 +3560,7 @@
ImeTracker.forLogging().onProgress(statsToken, ImeTracker.PHASE_SERVER_HAS_IME);
mCurStatsToken = null;
- if (!Flags.useHandwritingListenerForTooltype()
- && lastClickToolType != MotionEvent.TOOL_TYPE_UNKNOWN) {
+ if (lastClickToolType != MotionEvent.TOOL_TYPE_UNKNOWN) {
curMethod.updateEditorToolType(lastClickToolType);
}
mVisibilityApplier.performShowIme(windowToken, statsToken,
diff --git a/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java b/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java
index cec7a79..5d415c2 100644
--- a/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java
+++ b/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java
@@ -200,7 +200,9 @@
Slog.d(TAG, this + ": Starting");
}
mRunning = true;
- updateBinding();
+ if (!Flags.enablePreventionOfKeepAliveRouteProviders()) {
+ updateBinding();
+ }
}
if (rebindIfDisconnected && mActiveConnection == null && shouldBind()) {
unbind();
diff --git a/services/core/java/com/android/server/media/MediaRoute2ProviderWatcher.java b/services/core/java/com/android/server/media/MediaRoute2ProviderWatcher.java
index 233a3ab..fcca94b 100644
--- a/services/core/java/com/android/server/media/MediaRoute2ProviderWatcher.java
+++ b/services/core/java/com/android/server/media/MediaRoute2ProviderWatcher.java
@@ -150,7 +150,9 @@
mCallback.onAddProviderService(proxy);
} else if (sourceIndex >= targetIndex) {
MediaRoute2ProviderServiceProxy proxy = mProxies.get(sourceIndex);
- proxy.start(/* rebindIfDisconnected= */ true); // restart the proxy if needed
+ proxy.start(
+ /* rebindIfDisconnected= */
+ !Flags.enablePreventionOfKeepAliveRouteProviders());
Collections.swap(mProxies, sourceIndex, targetIndex++);
}
}
diff --git a/services/core/java/com/android/server/media/metrics/MediaMetricsManagerService.java b/services/core/java/com/android/server/media/metrics/MediaMetricsManagerService.java
index bbe6d3a..2cd8fe0 100644
--- a/services/core/java/com/android/server/media/metrics/MediaMetricsManagerService.java
+++ b/services/core/java/com/android/server/media/metrics/MediaMetricsManagerService.java
@@ -18,10 +18,13 @@
import android.content.Context;
import android.content.pm.PackageManager;
+import android.hardware.DataSpace;
import android.media.MediaMetrics;
+import android.media.codec.Enums;
import android.media.metrics.BundleSession;
import android.media.metrics.EditingEndedEvent;
import android.media.metrics.IMediaMetricsManager;
+import android.media.metrics.MediaItemInfo;
import android.media.metrics.NetworkEvent;
import android.media.metrics.PlaybackErrorEvent;
import android.media.metrics.PlaybackMetrics;
@@ -31,7 +34,9 @@
import android.os.PersistableBundle;
import android.provider.DeviceConfig;
import android.provider.DeviceConfig.Properties;
+import android.text.TextUtils;
import android.util.Base64;
+import android.util.Size;
import android.util.Slog;
import android.util.StatsEvent;
import android.util.StatsLog;
@@ -72,7 +77,14 @@
private static final String mMetricsId = MediaMetrics.Name.METRICS_MANAGER;
private static final String FAILED_TO_GET = "failed_to_get";
+
+ private static final MediaItemInfo EMPTY_MEDIA_ITEM_INFO = new MediaItemInfo.Builder().build();
+ private static final int DURATION_BUCKETS_BELOW_ONE_MINUTE = 8;
+ private static final int DURATION_BUCKETS_COUNT = 13;
+ private static final String AUDIO_MIME_TYPE_PREFIX = "audio/";
+ private static final String VIDEO_MIME_TYPE_PREFIX = "video/";
private final SecureRandom mSecureRandom;
+
@GuardedBy("mLock")
private Integer mMode = null;
@GuardedBy("mLock")
@@ -353,6 +365,51 @@
if (level == LOGGING_LEVEL_BLOCKED) {
return;
}
+ MediaItemInfo inputMediaItemInfo =
+ event.getInputMediaItemInfos().isEmpty()
+ ? EMPTY_MEDIA_ITEM_INFO
+ : event.getInputMediaItemInfos().get(0);
+ String inputAudioSampleMimeType =
+ getFilteredFirstMimeType(
+ inputMediaItemInfo.getSampleMimeTypes(), AUDIO_MIME_TYPE_PREFIX);
+ String inputVideoSampleMimeType =
+ getFilteredFirstMimeType(
+ inputMediaItemInfo.getSampleMimeTypes(), VIDEO_MIME_TYPE_PREFIX);
+ Size inputVideoSize = inputMediaItemInfo.getVideoSize();
+ int inputVideoResolution = getVideoResolutionEnum(inputVideoSize);
+ if (inputVideoResolution == Enums.RESOLUTION_UNKNOWN) {
+ // Try swapping width/height in case it's a portrait video.
+ inputVideoResolution =
+ getVideoResolutionEnum(
+ new Size(inputVideoSize.getHeight(), inputVideoSize.getWidth()));
+ }
+ List<String> inputCodecNames = inputMediaItemInfo.getCodecNames();
+ String inputFirstCodecName = !inputCodecNames.isEmpty() ? inputCodecNames.get(0) : "";
+ String inputSecondCodecName = inputCodecNames.size() > 1 ? inputCodecNames.get(1) : "";
+
+ MediaItemInfo outputMediaItemInfo =
+ event.getOutputMediaItemInfo() == null
+ ? EMPTY_MEDIA_ITEM_INFO
+ : event.getOutputMediaItemInfo();
+ String outputAudioSampleMimeType =
+ getFilteredFirstMimeType(
+ outputMediaItemInfo.getSampleMimeTypes(), AUDIO_MIME_TYPE_PREFIX);
+ String outputVideoSampleMimeType =
+ getFilteredFirstMimeType(
+ outputMediaItemInfo.getSampleMimeTypes(), VIDEO_MIME_TYPE_PREFIX);
+ Size outputVideoSize = outputMediaItemInfo.getVideoSize();
+ int outputVideoResolution = getVideoResolutionEnum(outputVideoSize);
+ if (outputVideoResolution == Enums.RESOLUTION_UNKNOWN) {
+ // Try swapping width/height in case it's a portrait video.
+ outputVideoResolution =
+ getVideoResolutionEnum(
+ new Size(outputVideoSize.getHeight(), outputVideoSize.getWidth()));
+ }
+ List<String> outputCodecNames = outputMediaItemInfo.getCodecNames();
+ String outputFirstCodecName =
+ !outputCodecNames.isEmpty() ? outputCodecNames.get(0) : "";
+ String outputSecondCodecName =
+ outputCodecNames.size() > 1 ? outputCodecNames.get(1) : "";
StatsEvent statsEvent =
StatsEvent.newBuilder()
.setAtomId(798)
@@ -360,6 +417,66 @@
.writeInt(event.getFinalState())
.writeInt(event.getErrorCode())
.writeLong(event.getTimeSinceCreatedMillis())
+ .writeInt(getThroughputFps(event))
+ .writeInt(event.getInputMediaItemInfos().size())
+ .writeInt(inputMediaItemInfo.getSourceType())
+ .writeLong(
+ getBucketedDurationMillis(
+ inputMediaItemInfo.getDurationMillis()))
+ .writeLong(
+ getBucketedDurationMillis(
+ inputMediaItemInfo.getClipDurationMillis()))
+ .writeString(
+ getFilteredMimeType(inputMediaItemInfo.getContainerMimeType()))
+ .writeString(inputAudioSampleMimeType)
+ .writeString(inputVideoSampleMimeType)
+ .writeInt(getCodecEnum(inputVideoSampleMimeType))
+ .writeInt(
+ getFilteredAudioSampleRateHz(
+ inputMediaItemInfo.getAudioSampleRateHz()))
+ .writeInt(inputMediaItemInfo.getAudioChannelCount())
+ .writeInt(inputVideoSize.getWidth())
+ .writeInt(inputVideoSize.getHeight())
+ .writeInt(inputVideoResolution)
+ .writeInt(getVideoResolutionAspectRatioEnum(inputVideoSize))
+ .writeInt(inputMediaItemInfo.getVideoDataSpace())
+ .writeInt(
+ getVideoHdrFormatEnum(
+ inputMediaItemInfo.getVideoDataSpace(),
+ inputVideoSampleMimeType))
+ .writeInt(Math.round(inputMediaItemInfo.getVideoFrameRate()))
+ .writeInt(getVideoFrameRateEnum(inputMediaItemInfo.getVideoFrameRate()))
+ .writeString(inputFirstCodecName)
+ .writeString(inputSecondCodecName)
+ .writeLong(
+ getBucketedDurationMillis(
+ outputMediaItemInfo.getDurationMillis()))
+ .writeLong(
+ getBucketedDurationMillis(
+ outputMediaItemInfo.getClipDurationMillis()))
+ .writeString(
+ getFilteredMimeType(outputMediaItemInfo.getContainerMimeType()))
+ .writeString(outputAudioSampleMimeType)
+ .writeString(outputVideoSampleMimeType)
+ .writeInt(getCodecEnum(outputVideoSampleMimeType))
+ .writeInt(
+ getFilteredAudioSampleRateHz(
+ outputMediaItemInfo.getAudioSampleRateHz()))
+ .writeInt(outputMediaItemInfo.getAudioChannelCount())
+ .writeInt(outputVideoSize.getWidth())
+ .writeInt(outputVideoSize.getHeight())
+ .writeInt(outputVideoResolution)
+ .writeInt(getVideoResolutionAspectRatioEnum(outputVideoSize))
+ .writeInt(outputMediaItemInfo.getVideoDataSpace())
+ .writeInt(
+ getVideoHdrFormatEnum(
+ outputMediaItemInfo.getVideoDataSpace(),
+ outputVideoSampleMimeType))
+ .writeInt(Math.round(outputMediaItemInfo.getVideoFrameRate()))
+ .writeInt(
+ getVideoFrameRateEnum(outputMediaItemInfo.getVideoFrameRate()))
+ .writeString(outputFirstCodecName)
+ .writeString(outputSecondCodecName)
.usePooledBuffer()
.build();
StatsLog.write(statsEvent);
@@ -511,4 +628,215 @@
}
}
}
+
+ private static int getThroughputFps(EditingEndedEvent event) {
+ MediaItemInfo outputMediaItemInfo = event.getOutputMediaItemInfo();
+ if (outputMediaItemInfo == null) {
+ return -1;
+ }
+ long videoSampleCount = outputMediaItemInfo.getVideoSampleCount();
+ if (videoSampleCount == MediaItemInfo.VALUE_UNSPECIFIED) {
+ return -1;
+ }
+ long elapsedTimeMs = event.getTimeSinceCreatedMillis();
+ if (elapsedTimeMs == EditingEndedEvent.TIME_SINCE_CREATED_UNKNOWN) {
+ return -1;
+ }
+ return (int)
+ Math.min(Integer.MAX_VALUE, Math.round(1000.0 * videoSampleCount / elapsedTimeMs));
+ }
+
+ private static long getBucketedDurationMillis(long durationMillis) {
+ if (durationMillis == MediaItemInfo.VALUE_UNSPECIFIED || durationMillis <= 0) {
+ return -1;
+ }
+ // Bucket values in an exponential distribution to reduce the precision that's stored:
+ // bucket index -> range -> bucketed duration
+ // 1 -> [0, 469 ms) -> 235 ms
+ // 2 -> [469 ms, 938 ms) -> 469 ms
+ // 3 -> [938 ms, 1875 ms) -> 938 ms
+ // 4 -> [1875 ms, 3750 ms) -> 1875 ms
+ // 5 -> [3750 ms, 7500 ms) -> 3750 ms
+ // [...]
+ // 13 -> [960000 ms, max) -> 960000 ms
+ int bucketIndex =
+ (int)
+ Math.floor(
+ DURATION_BUCKETS_BELOW_ONE_MINUTE
+ + Math.log((durationMillis + 1) / 60_000.0) / Math.log(2));
+ // Clamp to range [0, DURATION_BUCKETS_COUNT].
+ bucketIndex = Math.min(DURATION_BUCKETS_COUNT, Math.max(0, bucketIndex));
+ // Map back onto the representative value for the bucket.
+ return (long)
+ Math.ceil(Math.pow(2, bucketIndex - DURATION_BUCKETS_BELOW_ONE_MINUTE) * 60_000.0);
+ }
+
+ /**
+ * Returns the first entry in {@code mimeTypes} with the given prefix, if it matches the
+ * filtering allowlist. If no entries match the prefix or if the first matching entry is not on
+ * the allowlist, returns an empty string.
+ */
+ private static String getFilteredFirstMimeType(List<String> mimeTypes, String prefix) {
+ int size = mimeTypes.size();
+ for (int i = 0; i < size; i++) {
+ String mimeType = mimeTypes.get(i);
+ if (mimeType.startsWith(prefix)) {
+ return getFilteredMimeType(mimeType);
+ }
+ }
+ return "";
+ }
+
+ private static String getFilteredMimeType(String mimeType) {
+ if (TextUtils.isEmpty(mimeType)) {
+ return "";
+ }
+ // Discard all inputs that aren't allowlisted MIME types.
+ return switch (mimeType) {
+ case "video/mp4",
+ "video/x-matroska",
+ "video/webm",
+ "video/3gpp",
+ "video/avc",
+ "video/hevc",
+ "video/x-vnd.on2.vp8",
+ "video/x-vnd.on2.vp9",
+ "video/av01",
+ "video/mp2t",
+ "video/mp4v-es",
+ "video/mpeg",
+ "video/x-flv",
+ "video/dolby-vision",
+ "video/raw",
+ "audio/mp4",
+ "audio/mp4a-latm",
+ "audio/x-matroska",
+ "audio/webm",
+ "audio/mpeg",
+ "audio/mpeg-L1",
+ "audio/mpeg-L2",
+ "audio/ac3",
+ "audio/eac3",
+ "audio/eac3-joc",
+ "audio/av4",
+ "audio/true-hd",
+ "audio/vnd.dts",
+ "audio/vnd.dts.hd",
+ "audio/vorbis",
+ "audio/opus",
+ "audio/flac",
+ "audio/ogg",
+ "audio/wav",
+ "audio/midi",
+ "audio/raw",
+ "application/mp4",
+ "application/webm",
+ "application/x-matroska",
+ "application/dash+xml",
+ "application/x-mpegURL",
+ "application/vnd.ms-sstr+xml" ->
+ mimeType;
+ default -> "";
+ };
+ }
+
+ private static int getCodecEnum(String mimeType) {
+ if (TextUtils.isEmpty(mimeType)) {
+ return Enums.CODEC_UNKNOWN;
+ }
+ return switch (mimeType) {
+ case "video/avc" -> Enums.CODEC_AVC;
+ case "video/hevc" -> Enums.CODEC_HEVC;
+ case "video/x-vnd.on2.vp8" -> Enums.CODEC_VP8;
+ case "video/x-vnd.on2.vp9" -> Enums.CODEC_VP9;
+ case "video/av01" -> Enums.CODEC_AV1;
+ default -> Enums.CODEC_UNKNOWN;
+ };
+ }
+
+ private static int getFilteredAudioSampleRateHz(int sampleRateHz) {
+ return switch (sampleRateHz) {
+ case 8000, 11025, 16000, 22050, 44100, 48000, 96000, 192000 -> sampleRateHz;
+ default -> -1;
+ };
+ }
+
+ private static int getVideoResolutionEnum(Size size) {
+ int width = size.getWidth();
+ int height = size.getHeight();
+ if (width == 352 && height == 640) {
+ return Enums.RESOLUTION_352X640;
+ } else if (width == 360 && height == 640) {
+ return Enums.RESOLUTION_360X640;
+ } else if (width == 480 && height == 640) {
+ return Enums.RESOLUTION_480X640;
+ } else if (width == 480 && height == 854) {
+ return Enums.RESOLUTION_480X854;
+ } else if (width == 540 && height == 960) {
+ return Enums.RESOLUTION_540X960;
+ } else if (width == 576 && height == 1024) {
+ return Enums.RESOLUTION_576X1024;
+ } else if (width == 1280 && height == 720) {
+ return Enums.RESOLUTION_720P_HD;
+ } else if (width == 1920 && height == 1080) {
+ return Enums.RESOLUTION_1080P_FHD;
+ } else if (width == 1440 && height == 2560) {
+ return Enums.RESOLUTION_1440X2560;
+ } else if (width == 3840 && height == 2160) {
+ return Enums.RESOLUTION_4K_UHD;
+ } else if (width == 7680 && height == 4320) {
+ return Enums.RESOLUTION_8K_UHD;
+ } else {
+ return Enums.RESOLUTION_UNKNOWN;
+ }
+ }
+
+ private static int getVideoResolutionAspectRatioEnum(Size size) {
+ int width = size.getWidth();
+ int height = size.getHeight();
+ if (width <= 0 || height <= 0) {
+ return android.media.editing.Enums.RESOLUTION_ASPECT_RATIO_UNSPECIFIED;
+ } else if (width < height) {
+ return android.media.editing.Enums.RESOLUTION_ASPECT_RATIO_PORTRAIT;
+ } else if (height < width) {
+ return android.media.editing.Enums.RESOLUTION_ASPECT_RATIO_LANDSCAPE;
+ } else {
+ return android.media.editing.Enums.RESOLUTION_ASPECT_RATIO_SQUARE;
+ }
+ }
+
+ private static int getVideoHdrFormatEnum(int dataSpace, String mimeType) {
+ if (dataSpace == DataSpace.DATASPACE_UNKNOWN) {
+ return Enums.HDR_FORMAT_UNKNOWN;
+ }
+ if (mimeType.equals("video/dolby-vision")) {
+ return Enums.HDR_FORMAT_DOLBY_VISION;
+ }
+ int standard = DataSpace.getStandard(dataSpace);
+ int transfer = DataSpace.getTransfer(dataSpace);
+ if (standard == DataSpace.STANDARD_BT2020 && transfer == DataSpace.TRANSFER_HLG) {
+ return Enums.HDR_FORMAT_HLG;
+ }
+ if (standard == DataSpace.STANDARD_BT2020 && transfer == DataSpace.TRANSFER_ST2084) {
+ // We don't currently distinguish HDR10+ from HDR10.
+ return Enums.HDR_FORMAT_HDR10;
+ }
+ return Enums.HDR_FORMAT_NONE;
+ }
+
+ private static int getVideoFrameRateEnum(float frameRate) {
+ int frameRateInt = Math.round(frameRate);
+ return switch (frameRateInt) {
+ case 24 -> Enums.FRAMERATE_24;
+ case 25 -> Enums.FRAMERATE_25;
+ case 30 -> Enums.FRAMERATE_30;
+ case 50 -> Enums.FRAMERATE_50;
+ case 60 -> Enums.FRAMERATE_60;
+ case 120 -> Enums.FRAMERATE_120;
+ case 240 -> Enums.FRAMERATE_240;
+ case 480 -> Enums.FRAMERATE_480;
+ case 960 -> Enums.FRAMERATE_960;
+ default -> Enums.FRAMERATE_UNKNOWN;
+ };
+ }
}
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index d0c0543..f645eaa 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -16,6 +16,7 @@
package com.android.server.notification;
+import static android.app.Flags.FLAG_LIFETIME_EXTENSION_REFACTOR;
import static android.content.Context.BIND_ALLOW_WHITELIST_MANAGEMENT;
import static android.content.Context.BIND_AUTO_CREATE;
import static android.content.Context.BIND_FOREGROUND_SERVICE;
@@ -24,6 +25,7 @@
import static android.os.UserHandle.USER_SYSTEM;
import static android.service.notification.NotificationListenerService.META_DATA_DEFAULT_AUTOBIND;
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.app.ActivityManager;
import android.app.ActivityOptions;
@@ -1802,6 +1804,8 @@
public ComponentName component;
public int userid;
public boolean isSystem;
+ @FlaggedApi(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ public boolean isSystemUi;
public ServiceConnection connection;
public int targetSdkVersion;
public Pair<ComponentName, Integer> mKey;
@@ -1836,6 +1840,11 @@
return isSystem;
}
+ @FlaggedApi(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ public boolean isSystemUi() {
+ return isSystemUi;
+ }
+
@Override
public String toString() {
return new StringBuilder("ManagedServiceInfo[")
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index e7ad99a..3507d2d 100755
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -71,6 +71,7 @@
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_OFF;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_ON;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_STATUS_BAR;
+import static android.app.Flags.FLAG_LIFETIME_EXTENSION_REFACTOR;
import static android.app.Flags.lifetimeExtensionRefactor;
import static android.app.NotificationManager.zenModeFromInterruptionFilter;
import static android.app.StatusBarManager.ACTION_KEYGUARD_PRIVATE_NOTIFICATIONS_CHANGED;
@@ -159,6 +160,7 @@
import android.Manifest.permission;
import android.annotation.DurationMillisLong;
import android.annotation.ElapsedRealtimeLong;
+import android.annotation.FlaggedApi;
import android.annotation.MainThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -1852,6 +1854,7 @@
}
if (ACTION_NOTIFICATION_TIMEOUT.equals(action)) {
final NotificationRecord record;
+ // TODO: b/323013410 - Record should be cloned instead of used directly.
synchronized (mNotificationLock) {
record = findNotificationByKeyLocked(intent.getStringExtra(EXTRA_KEY));
}
@@ -1864,6 +1867,14 @@
FLAG_FOREGROUND_SERVICE | FLAG_USER_INITIATED_JOB
| FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY,
true, record.getUserId(), REASON_TIMEOUT, null);
+ // If cancellation will be prevented due to lifetime extension, we send an
+ // update to system UI.
+ synchronized (mNotificationLock) {
+ maybeNotifySystemUiListenerLifetimeExtendedLocked(record,
+ record.getSbn().getPackageName(),
+ mActivityManager.getPackageImportance(
+ record.getSbn().getPackageName()));
+ }
} else {
cancelNotification(record.getSbn().getUid(),
record.getSbn().getInitialPid(),
@@ -3825,7 +3836,17 @@
int mustNotHaveFlags = isCallingUidSystem() ? 0 :
(FLAG_FOREGROUND_SERVICE | FLAG_USER_INITIATED_JOB | FLAG_AUTOGROUP_SUMMARY);
if (lifetimeExtensionRefactor()) {
+ // Also don't allow client apps to cancel lifetime extended notifs.
mustNotHaveFlags |= FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY;
+ // If cancellation will be prevented due to lifetime extension, we send an update to
+ // system UI.
+ NotificationRecord record = null;
+ final int packageImportance = mActivityManager.getPackageImportance(pkg);
+ synchronized (mNotificationLock) {
+ record = findNotificationLocked(pkg, tag, id, userId);
+ maybeNotifySystemUiListenerLifetimeExtendedLocked(record, pkg,
+ packageImportance);
+ }
}
cancelNotificationInternal(pkg, opPkg, Binder.getCallingUid(), Binder.getCallingPid(),
@@ -3845,6 +3866,16 @@
pkg, null, 0, FLAG_FOREGROUND_SERVICE | FLAG_USER_INITIATED_JOB
| FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY,
userId, REASON_APP_CANCEL_ALL);
+ // If cancellation will be prevented due to lifetime extension, we send updates
+ // to system UI.
+ // In this case, we need to hold the lock to access these lists.
+ final int packageImportance = mActivityManager.getPackageImportance(pkg);
+ synchronized (mNotificationLock) {
+ notifySystemUiListenerLifetimeExtendedListLocked(mNotificationList,
+ packageImportance);
+ notifySystemUiListenerLifetimeExtendedListLocked(mEnqueuedNotifications,
+ packageImportance);
+ }
} else {
cancelAllNotificationsInt(Binder.getCallingUid(), Binder.getCallingPid(),
pkg, null, 0, FLAG_FOREGROUND_SERVICE | FLAG_USER_INITIATED_JOB,
@@ -4891,11 +4922,19 @@
final long identity = Binder.clearCallingIdentity();
boolean notificationsRapidlyCleared = false;
final String pkg;
+ final int packageImportance;
+ final ManagedServiceInfo info;
try {
synchronized (mNotificationLock) {
- final ManagedServiceInfo info = mListeners.checkServiceTokenLocked(token);
+ info = mListeners.checkServiceTokenLocked(token);
pkg = info.component.getPackageName();
-
+ }
+ if (lifetimeExtensionRefactor()) {
+ packageImportance = mActivityManager.getPackageImportance(pkg);
+ } else {
+ packageImportance = IMPORTANCE_NONE;
+ }
+ synchronized (mNotificationLock) {
// Cancellation reason. If the token comes from assistant, label the
// cancellation as coming from the assistant; default to LISTENER_CANCEL.
int reason = REASON_LISTENER_CANCEL;
@@ -4917,7 +4956,7 @@
|| isNotificationRecent(r.getUpdateTimeMs());
cancelNotificationFromListenerLocked(info, callingUid, callingPid,
r.getSbn().getPackageName(), r.getSbn().getTag(),
- r.getSbn().getId(), userId, reason);
+ r.getSbn().getId(), userId, reason, packageImportance);
}
} else {
for (NotificationRecord notificationRecord : mNotificationList) {
@@ -4931,6 +4970,12 @@
REASON_LISTENER_CANCEL_ALL, info, info.supportsProfiles(),
FLAG_ONGOING_EVENT | FLAG_NO_CLEAR
| FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY);
+ // If cancellation will be prevented due to lifetime extension, we send
+ // an update to system UI.
+ notifySystemUiListenerLifetimeExtendedListLocked(mNotificationList,
+ packageImportance);
+ notifySystemUiListenerLifetimeExtendedListLocked(mEnqueuedNotifications,
+ packageImportance);
} else {
cancelAllLocked(callingUid, callingPid, info.userid,
REASON_LISTENER_CANCEL_ALL, info, info.supportsProfiles(),
@@ -5051,10 +5096,14 @@
@GuardedBy("mNotificationLock")
private void cancelNotificationFromListenerLocked(ManagedServiceInfo info,
int callingUid, int callingPid, String pkg, String tag, int id, int userId,
- int reason) {
+ int reason, int packageImportance) {
int mustNotHaveFlags = FLAG_ONGOING_EVENT;
if (lifetimeExtensionRefactor()) {
mustNotHaveFlags |= FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY;
+ // If cancellation will be prevented due to lifetime extension, we send an update
+ // to system UI.
+ NotificationRecord record = findNotificationLocked(pkg, tag, id, userId);
+ maybeNotifySystemUiListenerLifetimeExtendedLocked(record, pkg, packageImportance);
}
cancelNotification(callingUid, callingPid, pkg, tag, id, 0 /* mustHaveFlags */,
mustNotHaveFlags,
@@ -5197,7 +5246,13 @@
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
final long identity = Binder.clearCallingIdentity();
+ final int packageImportance;
try {
+ if (lifetimeExtensionRefactor()) {
+ packageImportance = mActivityManager.getPackageImportance(pkg);
+ } else {
+ packageImportance = IMPORTANCE_NONE;
+ }
synchronized (mNotificationLock) {
final ManagedServiceInfo info = mListeners.checkServiceTokenLocked(token);
int cancelReason = REASON_LISTENER_CANCEL;
@@ -5210,7 +5265,7 @@
+ " use cancelNotification(key) instead.");
} else {
cancelNotificationFromListenerLocked(info, callingUid, callingPid,
- pkg, tag, id, info.userid, cancelReason);
+ pkg, tag, id, info.userid, cancelReason, packageImportance);
}
}
} finally {
@@ -11654,6 +11709,30 @@
});
}
+ @FlaggedApi(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ @GuardedBy("mNotificationLock")
+ private void notifySystemUiListenerLifetimeExtendedListLocked(
+ List<NotificationRecord> notificationList, int packageImportance) {
+ for (int i = notificationList.size() - 1; i >= 0; --i) {
+ NotificationRecord record = notificationList.get(i);
+ maybeNotifySystemUiListenerLifetimeExtendedLocked(record,
+ record.getSbn().getPackageName(), packageImportance);
+ }
+ }
+
+ @FlaggedApi(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ @GuardedBy("mNotificationLock")
+ private void maybeNotifySystemUiListenerLifetimeExtendedLocked(NotificationRecord record,
+ String pkg, int packageImportance) {
+ if (record != null && (record.getSbn().getNotification().flags
+ & FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY) > 0) {
+ boolean isAppForeground = pkg != null && packageImportance == IMPORTANCE_FOREGROUND;
+ mHandler.post(new EnqueueNotificationRunnable(record.getUser().getIdentifier(),
+ record, isAppForeground,
+ mPostNotificationTrackerFactory.newTracker(null)));
+ }
+ }
+
public class NotificationListeners extends ManagedServices {
static final String TAG_ENABLED_NOTIFICATION_LISTENERS = "enabled_listeners";
static final String TAG_REQUESTED_LISTENERS = "request_listeners";
@@ -11777,6 +11856,11 @@
@Override
public void onServiceAdded(ManagedServiceInfo info) {
+ if (lifetimeExtensionRefactor()) {
+ // Only System or System UI can call registerSystemService, so if the caller is not
+ // system, we know it's system UI.
+ info.isSystemUi = !isCallerSystemOrPhone();
+ }
final INotificationListener listener = (INotificationListener) info.service;
final NotificationRankingUpdate update;
synchronized (mNotificationLock) {
@@ -12141,6 +12225,23 @@
continue;
}
+ if (lifetimeExtensionRefactor()) {
+ // Checks if this is a request to notify system UI about a notification that
+ // has been lifetime extended.
+ // (We only need to check old for the flag, because in both cancellation and
+ // update cases, old should have the flag.)
+ // If it is such a request, and this is system UI, we send the post request
+ // only to System UI, and break as we don't need to continue checking other
+ // Managed Services.
+ if (info.isSystemUi() && old != null && old.getNotification() != null
+ && (old.getNotification().flags
+ & Notification.FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY) > 0) {
+ final NotificationRankingUpdate update = makeRankingUpdateLocked(info);
+ listenerCalls.add(() -> notifyPosted(info, oldSbn, update));
+ break;
+ }
+ }
+
// If we shouldn't notify all listeners, this means the hidden state of
// a notification was changed. Don't notifyPosted listeners targeting >= P.
// Instead, those listeners will receive notifyRankingUpdate.
diff --git a/services/core/java/com/android/server/notification/ZenLog.java b/services/core/java/com/android/server/notification/ZenLog.java
index 88d23ce..82c5733 100644
--- a/services/core/java/com/android/server/notification/ZenLog.java
+++ b/services/core/java/com/android/server/notification/ZenLog.java
@@ -28,6 +28,7 @@
import android.service.notification.NotificationListenerService;
import android.service.notification.ZenModeConfig;
import android.service.notification.ZenModeDiff;
+import android.util.LocalLog;
import android.util.Log;
import android.util.Slog;
@@ -37,26 +38,16 @@
import java.util.List;
public class ZenLog {
- private static final String TAG = "ZenLog";
- // the ZenLog is *very* verbose, so be careful about setting this to true
- private static final boolean DEBUG = false;
private static final int SIZE = Build.IS_DEBUGGABLE ? 200 : 100;
- private static final long[] TIMES = new long[SIZE];
- private static final int[] TYPES = new int[SIZE];
- private static final String[] MSGS = new String[SIZE];
-
- private static final SimpleDateFormat FORMAT = new SimpleDateFormat("MM-dd HH:mm:ss.SSS");
+ private static final LocalLog STATE_CHANGES = new LocalLog(SIZE);
+ private static final LocalLog INTERCEPTION_EVENTS = new LocalLog(SIZE);
private static final int TYPE_INTERCEPTED = 1;
- private static final int TYPE_ALLOW_DISABLE = 2;
private static final int TYPE_SET_RINGER_MODE_EXTERNAL = 3;
private static final int TYPE_SET_RINGER_MODE_INTERNAL = 4;
- private static final int TYPE_DOWNTIME = 5;
private static final int TYPE_SET_ZEN_MODE = 6;
- private static final int TYPE_UPDATE_ZEN_MODE = 7;
- private static final int TYPE_EXIT_CONDITION = 8;
private static final int TYPE_SUBSCRIBE = 9;
private static final int TYPE_UNSUBSCRIBE = 10;
private static final int TYPE_CONFIG = 11;
@@ -71,9 +62,6 @@
private static final int TYPE_CHECK_REPEAT_CALLER = 20;
private static final int TYPE_ALERT_ON_UPDATED_INTERCEPT = 21;
- private static int sNext;
- private static int sSize;
-
public static void traceIntercepted(NotificationRecord record, String reason) {
append(TYPE_INTERCEPTED, record.getKey() + "," + reason);
}
@@ -104,10 +92,6 @@
ringerModeToString(ringerModeExternalOut));
}
- public static void traceDowntimeAutotrigger(String result) {
- append(TYPE_DOWNTIME, result);
- }
-
public static void traceSetZenMode(int zenMode, String reason) {
append(TYPE_SET_ZEN_MODE, zenModeToString(zenMode) + "," + reason);
}
@@ -120,21 +104,12 @@
append(TYPE_SET_CONSOLIDATED_ZEN_POLICY, policy.toString() + "," + reason);
}
- public static void traceUpdateZenMode(int fromMode, int toMode) {
- append(TYPE_UPDATE_ZEN_MODE, zenModeToString(fromMode) + " -> " + zenModeToString(toMode));
- }
-
- public static void traceExitCondition(Condition c, ComponentName component, String reason) {
- append(TYPE_EXIT_CONDITION, c + "," + componentToString(component) + "," + reason);
- }
public static void traceSetNotificationPolicy(String pkg, int targetSdk,
NotificationManager.Policy policy) {
String policyLog = "pkg=" + pkg + " targetSdk=" + targetSdk
+ " NotificationPolicy=" + policy.toString();
append(TYPE_SET_NOTIFICATION_POLICY, policyLog);
- // TODO(b/180205791): remove when we can better surface apps that are changing policy
- Log.d(TAG, "Zen Policy Changed: " + policyLog);
}
public static void traceSubscribe(Uri uri, IConditionProvider provider, RemoteException e) {
@@ -145,13 +120,14 @@
append(TYPE_UNSUBSCRIBE, uri + "," + subscribeResult(provider, e));
}
- public static void traceConfig(String reason, ZenModeConfig oldConfig,
- ZenModeConfig newConfig) {
+ public static void traceConfig(String reason, ComponentName triggeringComponent,
+ ZenModeConfig oldConfig, ZenModeConfig newConfig, int callingUid) {
ZenModeDiff.ConfigDiff diff = new ZenModeDiff.ConfigDiff(oldConfig, newConfig);
if (diff == null || !diff.hasDiff()) {
append(TYPE_CONFIG, reason + " no changes");
} else {
append(TYPE_CONFIG, reason
+ + " - " + triggeringComponent + " : " + callingUid
+ ",\n" + (newConfig != null ? newConfig.toString() : null)
+ ",\n" + diff);
}
@@ -204,13 +180,9 @@
private static String typeToString(int type) {
switch (type) {
case TYPE_INTERCEPTED: return "intercepted";
- case TYPE_ALLOW_DISABLE: return "allow_disable";
case TYPE_SET_RINGER_MODE_EXTERNAL: return "set_ringer_mode_external";
case TYPE_SET_RINGER_MODE_INTERNAL: return "set_ringer_mode_internal";
- case TYPE_DOWNTIME: return "downtime";
case TYPE_SET_ZEN_MODE: return "set_zen_mode";
- case TYPE_UPDATE_ZEN_MODE: return "update_zen_mode";
- case TYPE_EXIT_CONDITION: return "exit_condition";
case TYPE_SUBSCRIBE: return "subscribe";
case TYPE_UNSUBSCRIBE: return "unsubscribe";
case TYPE_CONFIG: return "config";
@@ -278,30 +250,27 @@
}
private static void append(int type, String msg) {
- synchronized(MSGS) {
- TIMES[sNext] = System.currentTimeMillis();
- TYPES[sNext] = type;
- MSGS[sNext] = msg;
- sNext = (sNext + 1) % SIZE;
- if (sSize < SIZE) {
- sSize++;
+ if (type == TYPE_INTERCEPTED || type == TYPE_NOT_INTERCEPTED
+ || type == TYPE_CHECK_REPEAT_CALLER || type == TYPE_RECORD_CALLER
+ || type == TYPE_MATCHES_CALL_FILTER || type == TYPE_ALERT_ON_UPDATED_INTERCEPT) {
+ synchronized (INTERCEPTION_EVENTS) {
+ INTERCEPTION_EVENTS.log(typeToString(type) + ": " +msg);
+ }
+ } else {
+ synchronized (STATE_CHANGES) {
+ STATE_CHANGES.log(typeToString(type) + ": " +msg);
}
}
- if (DEBUG) Slog.d(TAG, typeToString(type) + ": " + msg);
}
public static void dump(PrintWriter pw, String prefix) {
- synchronized(MSGS) {
- final int start = (sNext - sSize + SIZE) % SIZE;
- for (int i = 0; i < sSize; i++) {
- final int j = (start + i) % SIZE;
- pw.print(prefix);
- pw.print(FORMAT.format(new Date(TIMES[j])));
- pw.print(' ');
- pw.print(typeToString(TYPES[j]));
- pw.print(": ");
- pw.println(MSGS[j]);
- }
+ synchronized (INTERCEPTION_EVENTS) {
+ pw.printf(prefix + "Interception Events:\n");
+ INTERCEPTION_EVENTS.dump(prefix, pw);
+ }
+ synchronized (STATE_CHANGES) {
+ pw.printf(prefix + "State Changes:\n");
+ STATE_CHANGES.dump(prefix, pw);
}
}
}
diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java
index aebd28a..1c20b2d 100644
--- a/services/core/java/com/android/server/notification/ZenModeHelper.java
+++ b/services/core/java/com/android/server/notification/ZenModeHelper.java
@@ -1713,7 +1713,7 @@
mConfigs.put(config.user, config);
}
if (DEBUG) Log.d(TAG, "setConfigLocked reason=" + reason, new Throwable());
- ZenLog.traceConfig(reason, mConfig, config);
+ ZenLog.traceConfig(reason, triggeringComponent, mConfig, config, callingUid);
// send some broadcasts
Policy newPolicy = getNotificationPolicy(config);
diff --git a/services/core/java/com/android/server/om/IdmapManager.java b/services/core/java/com/android/server/om/IdmapManager.java
index 25a39cc..86d05d9 100644
--- a/services/core/java/com/android/server/om/IdmapManager.java
+++ b/services/core/java/com/android/server/om/IdmapManager.java
@@ -257,7 +257,7 @@
private boolean matchesActorSignature(@NonNull AndroidPackage targetPackage,
@NonNull AndroidPackage overlayPackage, int userId) {
String targetOverlayableName = overlayPackage.getOverlayTargetOverlayableName();
- if (targetOverlayableName != null) {
+ if (targetOverlayableName != null && !mPackageManager.getNamedActors().isEmpty()) {
try {
OverlayableInfo overlayableInfo = mPackageManager.getOverlayableForTarget(
targetPackage.getPackageName(), targetOverlayableName, userId);
diff --git a/services/core/java/com/android/server/pm/AppDataHelper.java b/services/core/java/com/android/server/pm/AppDataHelper.java
index 1dd7905..18ba2cf 100644
--- a/services/core/java/com/android/server/pm/AppDataHelper.java
+++ b/services/core/java/com/android/server/pm/AppDataHelper.java
@@ -503,21 +503,24 @@
private void assertPackageStorageValid(@NonNull Computer snapshot, String volumeUuid,
String packageName, int userId) throws PackageManagerException {
final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
- final PackageUserStateInternal userState = packageState.getUserStateOrDefault(userId);
if (packageState == null) {
throw PackageManagerException.ofInternalError("Package " + packageName + " is unknown",
PackageManagerException.INTERNAL_ERROR_STORAGE_INVALID_PACKAGE_UNKNOWN);
- } else if (!TextUtils.equals(volumeUuid, packageState.getVolumeUuid())) {
+ }
+ if (!TextUtils.equals(volumeUuid, packageState.getVolumeUuid())) {
throw PackageManagerException.ofInternalError(
"Package " + packageName + " found on unknown volume " + volumeUuid
+ "; expected volume " + packageState.getVolumeUuid(),
PackageManagerException.INTERNAL_ERROR_STORAGE_INVALID_VOLUME_UNKNOWN);
- } else if (!userState.isInstalled() && !userState.dataExists()) {
+ }
+ final PackageUserStateInternal userState = packageState.getUserStateOrDefault(userId);
+ if (!userState.isInstalled() && !userState.dataExists()) {
throw PackageManagerException.ofInternalError(
"Package " + packageName + " not installed for user " + userId
+ " or was deleted without DELETE_KEEP_DATA",
PackageManagerException.INTERNAL_ERROR_STORAGE_INVALID_NOT_INSTALLED_FOR_USER);
- } else if (packageState.getPkg() != null
+ }
+ if (packageState.getPkg() != null
&& !shouldHaveAppStorage(packageState.getPkg())) {
throw PackageManagerException.ofInternalError(
"Package " + packageName + " shouldn't have storage",
diff --git a/services/core/java/com/android/server/pm/verify/domain/DomainVerificationManagerStub.java b/services/core/java/com/android/server/pm/verify/domain/DomainVerificationManagerStub.java
index 3f00a9d..7d90240 100644
--- a/services/core/java/com/android/server/pm/verify/domain/DomainVerificationManagerStub.java
+++ b/services/core/java/com/android/server/pm/verify/domain/DomainVerificationManagerStub.java
@@ -26,6 +26,7 @@
import android.content.pm.verify.domain.DomainVerificationManager;
import android.content.pm.verify.domain.DomainVerificationUserState;
import android.content.pm.verify.domain.IDomainVerificationManager;
+import android.os.Bundle;
import android.os.ServiceSpecificException;
import java.util.List;
@@ -41,6 +42,27 @@
mService = service;
}
+ @Override
+ public void setUriRelativeFilterGroups(@NonNull String packageName,
+ @NonNull Bundle domainToGroupsBundle) {
+ try {
+ mService.setUriRelativeFilterGroups(packageName, domainToGroupsBundle);
+ } catch (Exception e) {
+ throw rethrow(e);
+ }
+ }
+
+ @NonNull
+ @Override
+ public Bundle getUriRelativeFilterGroups(
+ @NonNull String packageName, @NonNull List<String> domains) {
+ try {
+ return mService.getUriRelativeFilterGroups(packageName, domains);
+ } catch (Exception e) {
+ throw rethrow(e);
+ }
+ }
+
@NonNull
@Override
public List<String> queryValidVerificationPackageNames() {
diff --git a/services/core/java/com/android/server/pm/verify/domain/DomainVerificationPersistence.java b/services/core/java/com/android/server/pm/verify/domain/DomainVerificationPersistence.java
index ac6d795..de464a4 100644
--- a/services/core/java/com/android/server/pm/verify/domain/DomainVerificationPersistence.java
+++ b/services/core/java/com/android/server/pm/verify/domain/DomainVerificationPersistence.java
@@ -19,6 +19,8 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
+import android.content.UriRelativeFilter;
+import android.content.UriRelativeFilterGroup;
import android.content.pm.Signature;
import android.content.pm.verify.domain.DomainVerificationState;
import android.os.UserHandle;
@@ -38,7 +40,10 @@
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
import java.util.UUID;
import java.util.function.Function;
@@ -67,6 +72,13 @@
public static final String TAG_DOMAIN = "domain";
public static final String ATTR_NAME = "name";
public static final String ATTR_STATE = "state";
+ public static final String TAG_URI_RELATIVE_FILTER_GROUPS = "uri-relative-filter-groups";
+ public static final String TAG_URI_RELATIVE_FILTER_GROUP = "uri-relative-filter-group";
+ public static final String ATTR_ACTION = "action";
+ public static final String TAG_URI_RELATIVE_FILTER = "uri-relative-filter";
+ public static final String ATTR_URI_PART = "uri-part";
+ public static final String ATTR_PATTERN_TYPE = "pattern-type";
+ public static final String ATTR_FILTER = "filter";
/**
* @param pkgNameToSignature Converts package name to a string representation of its signature.
@@ -176,6 +188,7 @@
final ArrayMap<String, Integer> stateMap = new ArrayMap<>();
final SparseArray<DomainVerificationInternalUserState> userStates = new SparseArray<>();
+ final ArrayMap<String, List<UriRelativeFilterGroup>> groupMap = new ArrayMap<>();
SettingsXml.ChildSection child = section.children();
while (child.moveToNext()) {
@@ -186,11 +199,47 @@
case TAG_USER_STATES:
readUserStates(child, userStates);
break;
+ case TAG_URI_RELATIVE_FILTER_GROUPS:
+ readUriRelativeFilterGroups(child, groupMap);
+ break;
}
}
return new DomainVerificationPkgState(packageName, id, hasAutoVerifyDomains, stateMap,
- userStates, signature);
+ userStates, signature, groupMap);
+ }
+
+ private static void readUriRelativeFilterGroups(@NonNull SettingsXml.ReadSection section,
+ @NonNull ArrayMap<String, List<UriRelativeFilterGroup>> groupMap) {
+ SettingsXml.ChildSection child = section.children();
+ while (child.moveToNext(TAG_DOMAIN)) {
+ String domain = child.getString(ATTR_NAME);
+ groupMap.put(domain, createUriRelativeFilterGroupsFromXml(child));
+ }
+ }
+
+ private static ArrayList<UriRelativeFilterGroup> createUriRelativeFilterGroupsFromXml(
+ @NonNull SettingsXml.ReadSection section) {
+ SettingsXml.ChildSection child = section.children();
+ ArrayList<UriRelativeFilterGroup> groups = new ArrayList<>();
+ while (child.moveToNext(TAG_URI_RELATIVE_FILTER_GROUP)) {
+ UriRelativeFilterGroup group = new UriRelativeFilterGroup(section.getInt(ATTR_ACTION));
+ readUriRelativeFiltersFromXml(child, group);
+ groups.add(group);
+ }
+ return groups;
+ }
+
+ private static void readUriRelativeFiltersFromXml(
+ @NonNull SettingsXml.ReadSection section, UriRelativeFilterGroup group) {
+ SettingsXml.ChildSection child = section.children();
+ while (child.moveToNext(TAG_URI_RELATIVE_FILTER)) {
+ String filter = child.getString(ATTR_FILTER);
+ if (filter != null) {
+ group.addUriRelativeFilter(new UriRelativeFilter(child.getInt(ATTR_URI_PART),
+ child.getInt(ATTR_PATTERN_TYPE), filter));
+ }
+ }
}
private static void readUserStates(@NonNull SettingsXml.ReadSection section,
@@ -236,6 +285,7 @@
.attribute(ATTR_SIGNATURE, signature)) {
writeStateMap(parentSection, pkgState.getStateMap());
writeUserStates(parentSection, userId, pkgState.getUserStates());
+ writeUriRelativeFilterGroupMap(parentSection, pkgState.getUriRelativeFilterGroupMap());
}
}
@@ -334,6 +384,52 @@
}
}
+ private static void writeUriRelativeFilterGroupMap(
+ @NonNull SettingsXml.WriteSection parentSection,
+ @NonNull ArrayMap<String, List<UriRelativeFilterGroup>> groupMap) throws IOException {
+ if (groupMap.isEmpty()) {
+ return;
+ }
+ try (SettingsXml.WriteSection section =
+ parentSection.startSection(TAG_URI_RELATIVE_FILTER_GROUPS)) {
+ for (int i = 0; i < groupMap.size(); i++) {
+ writeUriRelativeFilterGroups(section, groupMap.keyAt(i), groupMap.valueAt(i));
+ }
+ }
+ }
+
+ private static void writeUriRelativeFilterGroups(
+ @NonNull SettingsXml.WriteSection parentSection, @NonNull String domain,
+ @NonNull List<UriRelativeFilterGroup> groups) throws IOException {
+ if (groups.isEmpty()) {
+ return;
+ }
+ try (SettingsXml.WriteSection section =
+ parentSection.startSection(TAG_DOMAIN)
+ .attribute(ATTR_NAME, domain)) {
+ for (int i = 0; i < groups.size(); i++) {
+ writeUriRelativeFilterGroup(section, groups.get(i));
+ }
+ }
+ }
+
+ private static void writeUriRelativeFilterGroup(
+ @NonNull SettingsXml.WriteSection parentSection,
+ @NonNull UriRelativeFilterGroup group) throws IOException {
+ try (SettingsXml.WriteSection section =
+ parentSection.startSection(TAG_URI_RELATIVE_FILTER_GROUP)
+ .attribute(ATTR_ACTION, group.getAction())) {
+ Iterator<UriRelativeFilter> it = group.getUriRelativeFilters().iterator();
+ while (it.hasNext()) {
+ UriRelativeFilter filter = it.next();
+ section.startSection(TAG_URI_RELATIVE_FILTER)
+ .attribute(ATTR_URI_PART, filter.getUriPart())
+ .attribute(ATTR_PATTERN_TYPE, filter.getPatternType())
+ .attribute(ATTR_FILTER, filter.getFilter()).finish();
+ }
+ }
+ }
+
public static class ReadResult {
@NonNull
diff --git a/services/core/java/com/android/server/pm/verify/domain/DomainVerificationService.java b/services/core/java/com/android/server/pm/verify/domain/DomainVerificationService.java
index c796b40..305b087 100644
--- a/services/core/java/com/android/server/pm/verify/domain/DomainVerificationService.java
+++ b/services/core/java/com/android/server/pm/verify/domain/DomainVerificationService.java
@@ -19,14 +19,19 @@
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
+import android.Manifest;
import android.annotation.CheckResult;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
import android.annotation.SuppressLint;
import android.annotation.UserIdInt;
import android.compat.annotation.ChangeId;
import android.content.Context;
import android.content.Intent;
+import android.content.UriRelativeFilterGroup;
+import android.content.UriRelativeFilterGroupParcel;
+import android.content.pm.Flags;
import android.content.pm.IntentFilterVerificationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
@@ -38,6 +43,8 @@
import android.content.pm.verify.domain.DomainVerificationState;
import android.content.pm.verify.domain.DomainVerificationUserState;
import android.content.pm.verify.domain.IDomainVerificationManager;
+import android.net.Uri;
+import android.os.Bundle;
import android.os.UserHandle;
import android.util.ArrayMap;
import android.util.ArraySet;
@@ -223,6 +230,72 @@
mProxy = proxy;
}
+ /**
+ * Update the URI relative filter groups for a package's verified domains. All previously
+ * existing groups will be cleared before the new groups will be applied.
+ */
+ @RequiresPermission(Manifest.permission.DOMAIN_VERIFICATION_AGENT)
+ public void setUriRelativeFilterGroups(@NonNull String packageName,
+ @NonNull Bundle bundle)
+ throws NameNotFoundException {
+ getContext().enforceCallingOrSelfPermission(
+ android.Manifest.permission.DOMAIN_VERIFICATION_AGENT,
+ "Caller " + mConnection.getCallingUid() + " does not hold "
+ + android.Manifest.permission.DOMAIN_VERIFICATION_AGENT);
+ if (bundle.isEmpty()) {
+ return;
+ }
+ synchronized (mLock) {
+ DomainVerificationPkgState pkgState = mAttachedPkgStates.get(packageName);
+ if (pkgState == null) {
+ throw DomainVerificationUtils.throwPackageUnavailable(packageName);
+ }
+ Map<String, List<UriRelativeFilterGroup>> domainToGroupsMap =
+ pkgState.getUriRelativeFilterGroupMap();
+ for (String domain : bundle.keySet()) {
+ ArrayList<UriRelativeFilterGroupParcel> parcels =
+ bundle.getParcelableArrayList(domain, UriRelativeFilterGroupParcel.class);
+ domainToGroupsMap.put(domain, UriRelativeFilterGroup.parcelsToGroups(parcels));
+ }
+ }
+ }
+
+ /**
+ * Retrieve the current URI relative filter groups for a package's verified domain.
+ */
+ @NonNull
+ public Bundle getUriRelativeFilterGroups(@NonNull String packageName,
+ @NonNull List<String> domains) {
+ Bundle bundle = new Bundle();
+ synchronized (mLock) {
+ DomainVerificationPkgState pkgState = mAttachedPkgStates.get(packageName);
+ if (pkgState != null) {
+ Map<String, List<UriRelativeFilterGroup>> map =
+ pkgState.getUriRelativeFilterGroupMap();
+ for (int i = 0; i < domains.size(); i++) {
+ List<UriRelativeFilterGroup> groups = map.get(domains.get(i));
+ bundle.putParcelableList(domains.get(i),
+ UriRelativeFilterGroup.groupsToParcels(groups));
+ }
+ }
+ }
+ return bundle;
+ }
+
+ @NonNull
+ private List<UriRelativeFilterGroup> getUriRelativeFilterGroups(@NonNull String packageName,
+ @NonNull String domain) {
+ List<UriRelativeFilterGroup> groups = Collections.emptyList();
+ synchronized (mLock) {
+ DomainVerificationPkgState pkgState = mAttachedPkgStates.get(packageName);
+ if (pkgState != null) {
+ groups = pkgState.getUriRelativeFilterGroupMap().getOrDefault(domain,
+ Collections.emptyList());
+ }
+ }
+ return groups;
+ }
+
@NonNull
public List<String> queryValidVerificationPackageNames() {
mEnforcer.assertApprovedVerifier(mConnection.getCallingUid(), mProxy);
@@ -891,6 +964,8 @@
}
ArrayMap<String, Integer> oldStateMap = oldPkgState.getStateMap();
+ ArrayMap<String, List<UriRelativeFilterGroup>> oldGroups =
+ oldPkgState.getUriRelativeFilterGroupMap();
ArraySet<String> newAutoVerifyDomains =
mCollector.collectValidAutoVerifyDomains(newPkg);
int newDomainsSize = newAutoVerifyDomains.size();
@@ -941,7 +1016,7 @@
mAttachedPkgStates.put(pkgName, newDomainSetId, new DomainVerificationPkgState(
pkgName, newDomainSetId, hasAutoVerifyDomains, newStateMap, newUserStates,
- null /* signature */));
+ null /* signature */, oldGroups));
}
if (sendBroadcast) {
@@ -1572,8 +1647,6 @@
public Pair<List<ResolveInfo>, Integer> filterToApprovedApp(@NonNull Intent intent,
@NonNull List<ResolveInfo> infos, @UserIdInt int userId,
@NonNull Function<String, PackageStateInternal> pkgSettingFunction) {
- String domain = intent.getData().getHost();
-
// Collect valid infos
ArrayMap<ResolveInfo, Integer> infoApprovals = new ArrayMap<>();
int infosSize = infos.size();
@@ -1586,7 +1659,7 @@
}
// Find all approval levels
- int highestApproval = fillMapWithApprovalLevels(infoApprovals, domain, userId,
+ int highestApproval = fillMapWithApprovalLevels(infoApprovals, intent.getData(), userId,
pkgSettingFunction);
if (highestApproval <= APPROVAL_LEVEL_NONE) {
return Pair.create(emptyList(), highestApproval);
@@ -1623,12 +1696,23 @@
return Pair.create(finalList, highestApproval);
}
+ private boolean matchUriRelativeFilterGroups(Uri uri, String pkgName) {
+ if (uri.getHost() == null) {
+ return false;
+ }
+ List<UriRelativeFilterGroup> groups = getUriRelativeFilterGroups(pkgName, uri.getHost());
+ if (groups.isEmpty()) {
+ return true;
+ }
+ return UriRelativeFilterGroup.matchGroupsToUri(groups, uri);
+ }
+
/**
* @return highest approval level found
*/
@ApprovalLevel
private int fillMapWithApprovalLevels(@NonNull ArrayMap<ResolveInfo, Integer> inputMap,
- @NonNull String domain, @UserIdInt int userId,
+ @NonNull Uri uri, @UserIdInt int userId,
@NonNull Function<String, PackageStateInternal> pkgSettingFunction) {
int highestApproval = APPROVAL_LEVEL_NONE;
int size = inputMap.size();
@@ -1641,12 +1725,13 @@
ResolveInfo info = inputMap.keyAt(index);
final String packageName = info.getComponentInfo().packageName;
PackageStateInternal pkgSetting = pkgSettingFunction.apply(packageName);
- if (pkgSetting == null) {
+ if (pkgSetting == null || (Flags.relativeReferenceIntentFilters()
+ && !matchUriRelativeFilterGroups(uri, packageName))) {
fillInfoMapForSamePackage(inputMap, packageName, APPROVAL_LEVEL_NONE);
continue;
}
- int approval = approvalLevelForDomain(pkgSetting, domain, false, userId, DEBUG_APPROVAL,
- domain);
+ int approval = approvalLevelForDomain(pkgSetting, uri.getHost(), false, userId,
+ DEBUG_APPROVAL, uri.getHost());
highestApproval = Math.max(highestApproval, approval);
fillInfoMapForSamePackage(inputMap, packageName, approval);
}
diff --git a/services/core/java/com/android/server/pm/verify/domain/models/DomainVerificationPkgState.java b/services/core/java/com/android/server/pm/verify/domain/models/DomainVerificationPkgState.java
index d71dbbb..46051fe 100644
--- a/services/core/java/com/android/server/pm/verify/domain/models/DomainVerificationPkgState.java
+++ b/services/core/java/com/android/server/pm/verify/domain/models/DomainVerificationPkgState.java
@@ -19,6 +19,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
+import android.content.UriRelativeFilterGroup;
import android.content.pm.Signature;
import android.content.pm.verify.domain.DomainVerificationState;
import android.util.ArrayMap;
@@ -26,6 +27,7 @@
import com.android.internal.util.DataClass;
+import java.util.List;
import java.util.Objects;
import java.util.UUID;
@@ -77,15 +79,30 @@
@Nullable
private final String mBackupSignatureHash;
+ /**
+ * List of {@link UriRelativeFilterGroup} for filtering domains.
+ */
+ @NonNull
+ private final ArrayMap<String, List<UriRelativeFilterGroup>> mUriRelativeFilterGroupMap;
+
public DomainVerificationPkgState(@NonNull String packageName, @NonNull UUID id,
boolean hasAutoVerifyDomains) {
- this(packageName, id, hasAutoVerifyDomains, new ArrayMap<>(0), new SparseArray<>(0), null);
+ this(packageName, id, hasAutoVerifyDomains, new ArrayMap<>(0), new SparseArray<>(0), null,
+ new ArrayMap<>());
}
public DomainVerificationPkgState(@NonNull DomainVerificationPkgState pkgState,
@NonNull UUID id, boolean hasAutoVerifyDomains) {
this(pkgState.getPackageName(), id, hasAutoVerifyDomains, pkgState.getStateMap(),
- pkgState.getUserStates(), null);
+ pkgState.getUserStates(), null, new ArrayMap<>());
+ }
+
+ public DomainVerificationPkgState(@NonNull String packageName, @NonNull UUID id,
+ boolean hasAutoVerifyDomains, @NonNull ArrayMap<String, Integer> stateMap,
+ @NonNull SparseArray<DomainVerificationInternalUserState> userStates,
+ @Nullable String backupSignatureHash) {
+ this(packageName, id, hasAutoVerifyDomains, stateMap, userStates, backupSignatureHash,
+ new ArrayMap<>());
}
@Nullable
@@ -158,6 +175,8 @@
*
* It's assumed the domain verification agent will eventually re-verify this domain
* and revoke if necessary.
+ * @param uriRelativeFilterGroupMap
+ * List of {@link UriRelativeFilterGroup} for filtering domains.
*/
@DataClass.Generated.Member
public DomainVerificationPkgState(
@@ -166,7 +185,8 @@
boolean hasAutoVerifyDomains,
@NonNull ArrayMap<String,Integer> stateMap,
@NonNull SparseArray<DomainVerificationInternalUserState> userStates,
- @Nullable String backupSignatureHash) {
+ @Nullable String backupSignatureHash,
+ @NonNull ArrayMap<String,List<UriRelativeFilterGroup>> uriRelativeFilterGroupMap) {
this.mPackageName = packageName;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mPackageName);
@@ -181,6 +201,9 @@
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mUserStates);
this.mBackupSignatureHash = backupSignatureHash;
+ this.mUriRelativeFilterGroupMap = uriRelativeFilterGroupMap;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, mUriRelativeFilterGroupMap);
// onConstructed(); // You can define this method to get a callback
}
@@ -239,6 +262,14 @@
return mBackupSignatureHash;
}
+ /**
+ * List of {@link UriRelativeFilterGroup} for filtering domains.
+ */
+ @DataClass.Generated.Member
+ public @NonNull ArrayMap<String,List<UriRelativeFilterGroup>> getUriRelativeFilterGroupMap() {
+ return mUriRelativeFilterGroupMap;
+ }
+
@Override
@DataClass.Generated.Member
public String toString() {
@@ -251,7 +282,8 @@
"hasAutoVerifyDomains = " + mHasAutoVerifyDomains + ", " +
"stateMap = " + mStateMap + ", " +
"userStates = " + mUserStates + ", " +
- "backupSignatureHash = " + mBackupSignatureHash +
+ "backupSignatureHash = " + mBackupSignatureHash + ", " +
+ "uriRelativeFilterGroupMap = " + mUriRelativeFilterGroupMap +
" }";
}
@@ -273,7 +305,8 @@
&& mHasAutoVerifyDomains == that.mHasAutoVerifyDomains
&& Objects.equals(mStateMap, that.mStateMap)
&& userStatesEquals(that.mUserStates)
- && Objects.equals(mBackupSignatureHash, that.mBackupSignatureHash);
+ && Objects.equals(mBackupSignatureHash, that.mBackupSignatureHash)
+ && Objects.equals(mUriRelativeFilterGroupMap, that.mUriRelativeFilterGroupMap);
}
@Override
@@ -289,14 +322,15 @@
_hash = 31 * _hash + Objects.hashCode(mStateMap);
_hash = 31 * _hash + userStatesHashCode();
_hash = 31 * _hash + Objects.hashCode(mBackupSignatureHash);
+ _hash = 31 * _hash + Objects.hashCode(mUriRelativeFilterGroupMap);
return _hash;
}
@DataClass.Generated(
- time = 1617315369614L,
+ time = 1707351734724L,
codegenVersion = "1.0.23",
sourceFile = "frameworks/base/services/core/java/com/android/server/pm/verify/domain/models/DomainVerificationPkgState.java",
- inputSignatures = "private final @android.annotation.NonNull java.lang.String mPackageName\nprivate @android.annotation.NonNull java.util.UUID mId\nprivate final boolean mHasAutoVerifyDomains\nprivate final @android.annotation.NonNull android.util.ArrayMap<java.lang.String,java.lang.Integer> mStateMap\nprivate final @android.annotation.NonNull android.util.SparseArray<com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState> mUserStates\nprivate final @android.annotation.Nullable java.lang.String mBackupSignatureHash\npublic @android.annotation.Nullable com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState getUserState(int)\npublic @android.annotation.Nullable com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState getOrCreateUserState(int)\npublic void removeUser(int)\npublic void removeAllUsers()\nprivate int userStatesHashCode()\nprivate boolean userStatesEquals(android.util.SparseArray<com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState>)\nclass DomainVerificationPkgState extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genToString=true, genEqualsHashCode=true)")
+ inputSignatures = "private final @android.annotation.NonNull java.lang.String mPackageName\nprivate final @android.annotation.NonNull java.util.UUID mId\nprivate final boolean mHasAutoVerifyDomains\nprivate final @android.annotation.NonNull android.util.ArrayMap<java.lang.String,java.lang.Integer> mStateMap\nprivate final @android.annotation.NonNull android.util.SparseArray<com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState> mUserStates\nprivate final @android.annotation.Nullable java.lang.String mBackupSignatureHash\nprivate final @android.annotation.NonNull android.util.ArrayMap<java.lang.String,java.util.List<android.content.UriRelativeFilterGroup>> mUriRelativeFilterGroupMap\npublic @android.annotation.Nullable com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState getUserState(int)\npublic @android.annotation.Nullable com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState getOrCreateUserState(int)\npublic void removeUser(int)\npublic void removeAllUsers()\nprivate int userStatesHashCode()\nprivate boolean userStatesEquals(android.util.SparseArray<com.android.server.pm.verify.domain.models.DomainVerificationInternalUserState>)\nclass DomainVerificationPkgState extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genToString=true, genEqualsHashCode=true)")
@Deprecated
private void __metadata() {}
diff --git a/services/core/java/com/android/server/policy/DeviceStateProviderImpl.java b/services/core/java/com/android/server/policy/DeviceStateProviderImpl.java
index afcf5a0..76952b3 100644
--- a/services/core/java/com/android/server/policy/DeviceStateProviderImpl.java
+++ b/services/core/java/com/android/server/policy/DeviceStateProviderImpl.java
@@ -29,6 +29,7 @@
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
+import android.hardware.devicestate.DeviceState;
import android.os.Environment;
import android.os.PowerManager;
import android.util.ArrayMap;
@@ -40,7 +41,6 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
import com.android.server.LocalServices;
-import com.android.server.devicestate.DeviceState;
import com.android.server.devicestate.DeviceStateProvider;
import com.android.server.input.InputManagerInternal;
import com.android.server.policy.devicestate.config.Conditions;
diff --git a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
index 64cfc8d4..59766ec 100644
--- a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
+++ b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
@@ -45,11 +45,6 @@
import static android.hardware.SensorPrivacyManager.Sources.QS_TILE;
import static android.hardware.SensorPrivacyManager.Sources.SETTINGS;
import static android.hardware.SensorPrivacyManager.Sources.SHELL;
-import static android.hardware.SensorPrivacyManager.StateTypes.AUTOMOTIVE_DRIVER_ASSISTANCE_APPS;
-import static android.hardware.SensorPrivacyManager.StateTypes.AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS;
-import static android.hardware.SensorPrivacyManager.StateTypes.AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS;
-import static android.hardware.SensorPrivacyManager.StateTypes.DISABLED;
-import static android.hardware.SensorPrivacyManager.StateTypes.ENABLED;
import static android.hardware.SensorPrivacyManager.TOGGLE_TYPE_HARDWARE;
import static android.hardware.SensorPrivacyManager.TOGGLE_TYPE_SOFTWARE;
import static android.os.UserHandle.USER_NULL;
@@ -57,9 +52,6 @@
import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION;
import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__ACTION_UNKNOWN;
-import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_APPS;
-import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS;
-import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS;
import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__TOGGLE_OFF;
import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__TOGGLE_ON;
import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__SENSOR__CAMERA;
@@ -71,11 +63,8 @@
import static com.android.internal.util.FrameworkStatsLog.PRIVACY_SENSOR_TOGGLE_INTERACTION__SOURCE__SOURCE_UNKNOWN;
import static com.android.internal.util.FrameworkStatsLog.write;
-import android.Manifest;
-import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.app.ActivityManagerInternal;
@@ -98,7 +87,6 @@
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.graphics.drawable.Icon;
-import android.hardware.CameraPrivacyAllowlistEntry;
import android.hardware.ISensorPrivacyListener;
import android.hardware.ISensorPrivacyManager;
import android.hardware.SensorPrivacyManager;
@@ -135,7 +123,6 @@
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
-import com.android.internal.camera.flags.Flags;
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.os.BackgroundThread;
import com.android.internal.util.DumpUtils;
@@ -144,7 +131,6 @@
import com.android.internal.util.function.pooled.PooledLambda;
import com.android.server.FgThread;
import com.android.server.LocalServices;
-import com.android.server.SystemConfig;
import com.android.server.SystemService;
import com.android.server.pm.UserManagerInternal;
@@ -153,7 +139,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
@@ -169,24 +154,7 @@
SensorPrivacyService.class.getName() + ".action.disable_sensor_privacy";
public static final int REMINDER_DIALOG_DELAY_MILLIS = 500;
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private static final int ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS =
- PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS;
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private static final int ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS =
- PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS;
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private static final int ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_APPS =
- PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_APPS;
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private static final int ACTION__TOGGLE_ON =
- PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__TOGGLE_ON;
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private static final int ACTION__TOGGLE_OFF =
- PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__TOGGLE_OFF;
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private static final int ACTION__ACTION_UNKNOWN =
- PRIVACY_SENSOR_TOGGLE_INTERACTION__ACTION__ACTION_UNKNOWN;
+
private final Context mContext;
private final SensorPrivacyServiceImpl mSensorPrivacyServiceImpl;
private final UserManagerInternal mUserManagerInternal;
@@ -208,9 +176,6 @@
private CallStateHelper mCallStateHelper;
private KeyguardManager mKeyguardManager;
- List<CameraPrivacyAllowlistEntry> mCameraPrivacyAllowlist =
- new ArrayList<CameraPrivacyAllowlistEntry>();
-
private int mCurrentUser = USER_NULL;
public SensorPrivacyService(Context context) {
@@ -227,15 +192,6 @@
mPackageManagerInternal = getLocalService(PackageManagerInternal.class);
mNotificationManager = mContext.getSystemService(NotificationManager.class);
mSensorPrivacyServiceImpl = new SensorPrivacyServiceImpl();
- ArrayMap<String, Boolean> cameraPrivacyAllowlist =
- SystemConfig.getInstance().getCameraPrivacyAllowlist();
-
- for (Map.Entry<String, Boolean> entry : cameraPrivacyAllowlist.entrySet()) {
- CameraPrivacyAllowlistEntry ent = new CameraPrivacyAllowlistEntry();
- ent.packageName = entry.getKey();
- ent.isMandatory = entry.getValue();
- mCameraPrivacyAllowlist.add(ent);
- }
}
@Override
@@ -368,15 +324,8 @@
mHandler, mHandler::handleSensorPrivacyChanged);
mSensorPrivacyStateController.setSensorPrivacyListener(
mHandler,
- (toggleType, userId, sensor, state) -> {
- mHandler.handleSensorPrivacyChanged(
- userId, toggleType, sensor, state.isEnabled());
- if (Flags.privacyAllowlist()) {
- mHandler.handleSensorPrivacyChanged(
- userId, toggleType, sensor, state.getState());
- }
- });
-
+ (toggleType, userId, sensor, state) -> mHandler.handleSensorPrivacyChanged(
+ userId, toggleType, sensor, state.isEnabled()));
}
// If sensor privacy is enabled for a sensor, but the device doesn't support sensor privacy
@@ -451,15 +400,9 @@
* @param packageName The package name of the app using the sensor
* @param sensor The sensor that is attempting to be used
*/
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
private void onSensorUseStarted(int uid, String packageName, int sensor) {
UserHandle user = UserHandle.of(mCurrentUser);
-
- if (Flags.privacyAllowlist() && (sensor == CAMERA) && isAutomotive(mContext)) {
- if (!isCameraPrivacyEnabled(packageName)) {
- return;
- }
- } else if (!isCombinedToggleSensorPrivacyEnabled(sensor)) {
+ if (!isCombinedToggleSensorPrivacyEnabled(sensor)) {
return;
}
@@ -784,12 +727,6 @@
== Configuration.UI_MODE_TYPE_TELEVISION;
}
- private boolean isAutomotive(Context context) {
- int uiMode = context.getResources().getConfiguration().uiMode;
- return (uiMode & Configuration.UI_MODE_TYPE_MASK)
- == Configuration.UI_MODE_TYPE_CAR;
- }
-
/**
* Sets the sensor privacy to the provided state and notifies all listeners of the new
* state.
@@ -829,225 +766,6 @@
setToggleSensorPrivacyUnchecked(TOGGLE_TYPE_SOFTWARE, userId, source, sensor, enable);
}
-
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
- public void setToggleSensorPrivacyState(int userId, int source, int sensor, int state) {
- if (DEBUG) {
- Log.d(TAG, "callingUid=" + Binder.getCallingUid()
- + " callingPid=" + Binder.getCallingPid()
- + " setToggleSensorPrivacyState("
- + "userId=" + userId
- + " source=" + source
- + " sensor=" + sensor
- + " state=" + state
- + ")");
- }
- enforceManageSensorPrivacyPermission();
- if (userId == UserHandle.USER_CURRENT) {
- userId = mCurrentUser;
- }
-
- if (!canChangeToggleSensorPrivacy(userId, sensor)) {
- return;
- }
- if (!supportsSensorToggle(TOGGLE_TYPE_SOFTWARE, sensor)) {
- // Do not enable sensor privacy if the device doesn't support it.
- return;
- }
-
- setToggleSensorPrivacyStateUnchecked(TOGGLE_TYPE_SOFTWARE, userId, source, sensor,
- state);
- }
-
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private void setToggleSensorPrivacyStateUnchecked(int toggleType, int userId, int source,
- int sensor, int state) {
- if (DEBUG) {
- Log.d(TAG, "callingUid=" + Binder.getCallingUid()
- + " callingPid=" + Binder.getCallingPid()
- + " setToggleSensorPrivacyStateUnchecked("
- + "userId=" + userId
- + " source=" + source
- + " sensor=" + sensor
- + " state=" + state
- + ")");
- }
- long[] lastChange = new long[1];
- mSensorPrivacyStateController.atomic(() -> {
- SensorState sensorState = mSensorPrivacyStateController
- .getState(toggleType, userId, sensor);
- lastChange[0] = sensorState.getLastChange();
- mSensorPrivacyStateController.setState(
- toggleType, userId, sensor, state, mHandler,
- changeSuccessful -> {
- if (changeSuccessful) {
- if (userId == mUserManagerInternal.getProfileParentId(userId)) {
- mHandler.sendMessage(PooledLambda.obtainMessage(
- SensorPrivacyServiceImpl::logSensorPrivacyStateToggle,
- this,
- source, sensor, state, lastChange[0], false));
- }
- }
- });
- });
- }
-
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- private void logSensorPrivacyStateToggle(int source, int sensor, int state,
- long lastChange, boolean onShutDown) {
- long logMins = Math.max(0, (getCurrentTimeMillis() - lastChange) / (1000 * 60));
-
- int logAction = ACTION__ACTION_UNKNOWN;
- if (!onShutDown) {
- switch(state) {
- case ENABLED :
- logAction = ACTION__TOGGLE_OFF;
- break;
- case DISABLED :
- logAction = ACTION__TOGGLE_ON;
- break;
- case AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS :
- logAction = ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS;
- break;
- case AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS :
- logAction = ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS;
- break;
- case AUTOMOTIVE_DRIVER_ASSISTANCE_APPS :
- logAction = ACTION__AUTOMOTIVE_DRIVER_ASSISTANCE_APPS;
- break;
- default :
- logAction = ACTION__ACTION_UNKNOWN;
- break;
- }
- }
-
- int logSensor = PRIVACY_SENSOR_TOGGLE_INTERACTION__SENSOR__SENSOR_UNKNOWN;
- switch(sensor) {
- case CAMERA:
- logSensor = PRIVACY_SENSOR_TOGGLE_INTERACTION__SENSOR__CAMERA;
- break;
- case MICROPHONE:
- logSensor = PRIVACY_SENSOR_TOGGLE_INTERACTION__SENSOR__MICROPHONE;
- break;
- default:
- logSensor = PRIVACY_SENSOR_TOGGLE_INTERACTION__SENSOR__SENSOR_UNKNOWN;
- break;
- }
-
- int logSource = PRIVACY_SENSOR_TOGGLE_INTERACTION__SOURCE__SOURCE_UNKNOWN;
- switch(source) {
- case QS_TILE :
- logSource = PRIVACY_SENSOR_TOGGLE_INTERACTION__SOURCE__QS_TILE;
- break;
- case DIALOG :
- logSource = PRIVACY_SENSOR_TOGGLE_INTERACTION__SOURCE__DIALOG;
- break;
- case SETTINGS:
- logSource = PRIVACY_SENSOR_TOGGLE_INTERACTION__SOURCE__SETTINGS;
- break;
- default:
- logSource = PRIVACY_SENSOR_TOGGLE_INTERACTION__SOURCE__SOURCE_UNKNOWN;
- break;
- }
-
- if (DEBUG || DEBUG_LOGGING) {
- Log.d(TAG, "Logging sensor toggle interaction:" + " logSensor=" + logSensor
- + " logAction=" + logAction + " logSource=" + logSource + " logMins="
- + logMins);
- }
- write(PRIVACY_SENSOR_TOGGLE_INTERACTION, logSensor, logAction, logSource, logMins);
-
- }
-
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
- public void setToggleSensorPrivacyStateForProfileGroup(int userId, int source, int sensor,
- int state) {
- enforceManageSensorPrivacyPermission();
- if (userId == UserHandle.USER_CURRENT) {
- userId = mCurrentUser;
- }
- int parentId = mUserManagerInternal.getProfileParentId(userId);
- forAllUsers(userId2 -> {
- if (parentId == mUserManagerInternal.getProfileParentId(userId2)) {
- setToggleSensorPrivacyState(userId2, source, sensor, state);
- }
- });
- }
-
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
- public List<CameraPrivacyAllowlistEntry> getCameraPrivacyAllowlist() {
- enforceObserveSensorPrivacyPermission();
- return mCameraPrivacyAllowlist;
- }
-
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
- public boolean isCameraPrivacyEnabled(String packageName) {
- if (DEBUG) {
- Log.d(TAG, "callingUid=" + Binder.getCallingUid()
- + " callingPid=" + Binder.getCallingPid()
- + " isCameraPrivacyEnabled("
- + "packageName=" + packageName
- + ")");
- }
- enforceObserveSensorPrivacyPermission();
-
- int state = mSensorPrivacyStateController.getState(TOGGLE_TYPE_SOFTWARE, mCurrentUser,
- CAMERA).getState();
- if (state == ENABLED) {
- return true;
- } else if (state == DISABLED) {
- return false;
- } else if (state == AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS) {
- for (CameraPrivacyAllowlistEntry entry : mCameraPrivacyAllowlist) {
- if ((packageName.equals(entry.packageName)) && !entry.isMandatory) {
- return false;
- }
- }
- return true;
- } else if (state == AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS) {
- for (CameraPrivacyAllowlistEntry entry : mCameraPrivacyAllowlist) {
- if ((packageName.equals(entry.packageName)) && entry.isMandatory) {
- return false;
- }
- }
- return true;
- } else if (state == AUTOMOTIVE_DRIVER_ASSISTANCE_APPS) {
- for (CameraPrivacyAllowlistEntry entry : mCameraPrivacyAllowlist) {
- if (packageName.equals(entry.packageName)) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
-
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
- public int getToggleSensorPrivacyState(int toggleType, int sensor) {
- if (DEBUG) {
- Log.d(TAG, "callingUid=" + Binder.getCallingUid()
- + " callingPid=" + Binder.getCallingPid()
- + " getToggleSensorPrivacyState("
- + "toggleType=" + toggleType
- + " sensor=" + sensor
- + ")");
- }
- enforceObserveSensorPrivacyPermission();
-
- return mSensorPrivacyStateController.getState(toggleType, mCurrentUser, sensor)
- .getState();
- }
-
private void setToggleSensorPrivacyUnchecked(int toggleType, int userId, int source,
int sensor, boolean enable) {
if (DEBUG) {
@@ -1181,23 +899,16 @@
* Enforces the caller contains the necessary permission to change the state of sensor
* privacy.
*/
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
private void enforceManageSensorPrivacyPermission() {
- if (mContext.checkCallingOrSelfPermission(
- android.Manifest.permission.MANAGE_SENSOR_PRIVACY) == PERMISSION_GRANTED) {
- return;
- }
-
- String message = "Changing sensor privacy requires the following permission: "
- + MANAGE_SENSOR_PRIVACY;
- throw new SecurityException(message);
+ enforcePermission(android.Manifest.permission.MANAGE_SENSOR_PRIVACY,
+ "Changing sensor privacy requires the following permission: "
+ + MANAGE_SENSOR_PRIVACY);
}
/**
* Enforces the caller contains the necessary permission to observe changes to the sate of
* sensor privacy.
*/
- @RequiresPermission(Manifest.permission.OBSERVE_SENSOR_PRIVACY)
private void enforceObserveSensorPrivacyPermission() {
String systemUIPackage = mContext.getString(R.string.config_systemUi);
int systemUIAppId = UserHandle.getAppId(mPackageManagerInternal
@@ -1206,13 +917,15 @@
// b/221782106, possible race condition with role grant might bootloop device.
return;
}
- if (mContext.checkCallingOrSelfPermission(
- android.Manifest.permission.OBSERVE_SENSOR_PRIVACY) == PERMISSION_GRANTED) {
+ enforcePermission(android.Manifest.permission.OBSERVE_SENSOR_PRIVACY,
+ "Observing sensor privacy changes requires the following permission: "
+ + android.Manifest.permission.OBSERVE_SENSOR_PRIVACY);
+ }
+
+ private void enforcePermission(String permission, String message) {
+ if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
return;
}
-
- String message = "Observing sensor privacy changes requires the following permission: "
- + android.Manifest.permission.OBSERVE_SENSOR_PRIVACY;
throw new SecurityException(message);
}
@@ -1580,13 +1293,11 @@
}
@Override
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
public void onShellCommand(FileDescriptor in, FileDescriptor out,
FileDescriptor err, String[] args, ShellCallback callback,
ResultReceiver resultReceiver) {
(new ShellCommand() {
@Override
- @RequiresPermission(Manifest.permission.MANAGE_SENSOR_PRIVACY)
public int onCommand(String cmd) {
if (cmd == null) {
return handleDefaultCommands(cmd);
@@ -1616,45 +1327,6 @@
setToggleSensorPrivacy(userId, SHELL, sensor, false);
}
break;
- case "automotive_driver_assistance_apps" : {
- if (Flags.privacyAllowlist()) {
- int sensor = sensorStrToId(getNextArgRequired());
- if ((!isAutomotive(mContext)) || (sensor != CAMERA)) {
- pw.println("Command not valid for this sensor");
- return -1;
- }
-
- setToggleSensorPrivacyState(userId, SHELL, sensor,
- AUTOMOTIVE_DRIVER_ASSISTANCE_APPS);
- }
- }
- break;
- case "automotive_driver_assistance_helpful_apps" : {
- if (Flags.privacyAllowlist()) {
- int sensor = sensorStrToId(getNextArgRequired());
- if ((!isAutomotive(mContext)) || (sensor != CAMERA)) {
- pw.println("Command not valid for this sensor");
- return -1;
- }
-
- setToggleSensorPrivacyState(userId, SHELL, sensor,
- AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS);
- }
- }
- break;
- case "automotive_driver_assistance_required_apps" : {
- if (Flags.privacyAllowlist()) {
- int sensor = sensorStrToId(getNextArgRequired());
- if ((!isAutomotive(mContext)) || (sensor != CAMERA)) {
- pw.println("Command not valid for this sensor");
- return -1;
- }
-
- setToggleSensorPrivacyState(userId, SHELL, sensor,
- AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS);
- }
- }
- break;
default:
return handleDefaultCommands(cmd);
}
@@ -1677,24 +1349,6 @@
pw.println(" disable USER_ID SENSOR");
pw.println(" Disable privacy for a certain sensor.");
pw.println("");
- if (Flags.privacyAllowlist()) {
- if (isAutomotive(mContext)) {
- pw.println(" automotive_driver_assistance_apps USER_ID SENSOR");
- pw.println(" Disable privacy for automotive apps which help you"
- + " drive and apps which are required by OEM");
- pw.println("");
- pw.println(" automotive_driver_assistance_helpful_apps "
- + "USER_ID SENSOR");
- pw.println(" Disable privacy for automotive apps which "
- + "help you drive.");
- pw.println("");
- pw.println(" automotive_driver_assistance_required_apps "
- + "USER_ID SENSOR");
- pw.println(" Disable privacy for automotive apps which are "
- + "required by OEM.");
- pw.println("");
- }
- }
}
}).exec(this, in, out, err, args, callback, resultReceiver);
}
@@ -1803,38 +1457,6 @@
mSensorPrivacyServiceImpl.showSensorStateChangedActivity(sensor, toggleType);
}
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- public void handleSensorPrivacyChanged(int userId, int toggleType, int sensor,
- int state) {
- if (userId == mCurrentUser) {
- mSensorPrivacyServiceImpl.setGlobalRestriction(sensor,
- mSensorPrivacyServiceImpl.isCombinedToggleSensorPrivacyEnabled(sensor));
- }
-
- if (userId != mCurrentUser) {
- return;
- }
- synchronized (mListenerLock) {
- try {
- final int count = mToggleSensorListeners.beginBroadcast();
- for (int i = 0; i < count; i++) {
- ISensorPrivacyListener listener = mToggleSensorListeners.getBroadcastItem(
- i);
- try {
- listener.onSensorPrivacyStateChanged(toggleType, sensor, state);
- } catch (RemoteException e) {
- Log.e(TAG, "Caught an exception notifying listener " + listener + ": ",
- e);
- }
- }
- } finally {
- mToggleSensorListeners.finishBroadcast();
- }
- }
-
- mSensorPrivacyServiceImpl.showSensorStateChangedActivity(sensor, toggleType);
- }
-
public void removeSuppressPackageReminderToken(Pair<Integer, UserHandle> key,
IBinder token) {
sendMessage(PooledLambda.obtainMessage(
diff --git a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateController.java b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateController.java
index 0e29222..9694958 100644
--- a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateController.java
+++ b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateController.java
@@ -16,11 +16,9 @@
package com.android.server.sensorprivacy;
-import android.annotation.FlaggedApi;
import android.os.Handler;
import com.android.internal.annotations.GuardedBy;
-import com.android.internal.camera.flags.Flags;
import com.android.internal.util.dump.DualDumpOutputStream;
import com.android.internal.util.function.pooled.PooledLambda;
@@ -53,14 +51,6 @@
}
}
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- void setState(int toggleType, int userId, int sensor, int state, Handler callbackHandler,
- SetStateResultCallback callback) {
- synchronized (mLock) {
- setStateLocked(toggleType, userId, sensor, state, callbackHandler, callback);
- }
- }
-
void setSensorPrivacyListener(Handler handler,
SensorPrivacyListener listener) {
synchronized (mLock) {
@@ -138,11 +128,6 @@
Handler callbackHandler, SetStateResultCallback callback);
@GuardedBy("mLock")
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- abstract void setStateLocked(int toggleType, int userId, int sensor, int state,
- Handler callbackHandler, SetStateResultCallback callback);
-
- @GuardedBy("mLock")
abstract void setSensorPrivacyListenerLocked(Handler handler,
SensorPrivacyListener listener);
diff --git a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateControllerImpl.java b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateControllerImpl.java
index 2d96aeb..3dcb4cf 100644
--- a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateControllerImpl.java
+++ b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyStateControllerImpl.java
@@ -16,12 +16,8 @@
package com.android.server.sensorprivacy;
-import static android.hardware.SensorPrivacyManager.StateTypes.DISABLED;
-
-import android.annotation.FlaggedApi;
import android.os.Handler;
-import com.android.internal.camera.flags.Flags;
import com.android.internal.util.dump.DualDumpOutputStream;
import com.android.internal.util.function.pooled.PooledLambda;
@@ -89,33 +85,6 @@
sendSetStateCallback(callbackHandler, callback, false);
}
- @Override
- @FlaggedApi(Flags.FLAG_PRIVACY_ALLOWLIST)
- void setStateLocked(int toggleType, int userId, int sensor, int state,
- Handler callbackHandler, SetStateResultCallback callback) {
- // Changing the SensorState's mEnabled updates the timestamp of its last change.
- // A nonexistent state -> unmuted should not set the timestamp.
- SensorState lastState = mPersistedState.getState(toggleType, userId, sensor);
- if (lastState == null) {
- if (state == DISABLED) {
- sendSetStateCallback(callbackHandler, callback, false);
- return;
- } else {
- SensorState sensorState = new SensorState(state);
- mPersistedState.setState(toggleType, userId, sensor, sensorState);
- notifyStateChangeLocked(toggleType, userId, sensor, sensorState);
- sendSetStateCallback(callbackHandler, callback, true);
- return;
- }
- }
- if (lastState.setState(state)) {
- notifyStateChangeLocked(toggleType, userId, sensor, lastState);
- sendSetStateCallback(callbackHandler, callback, true);
- return;
- }
- sendSetStateCallback(callbackHandler, callback, false);
- }
-
private void notifyStateChangeLocked(int toggleType, int userId, int sensor,
SensorState sensorState) {
if (mListenerHandler != null && mListener != null) {
diff --git a/services/core/java/com/android/server/wm/DragDropController.java b/services/core/java/com/android/server/wm/DragDropController.java
index 6a3cf43..a3e2869 100644
--- a/services/core/java/com/android/server/wm/DragDropController.java
+++ b/services/core/java/com/android/server/wm/DragDropController.java
@@ -16,6 +16,9 @@
package com.android.server.wm;
+import static android.view.View.DRAG_FLAG_GLOBAL;
+import static android.view.View.DRAG_FLAG_GLOBAL_SAME_APPLICATION;
+
import static com.android.input.flags.Flags.enablePointerChoreographer;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
@@ -30,15 +33,20 @@
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
+import android.os.RemoteException;
import android.util.Slog;
import android.view.Display;
+import android.view.DragEvent;
import android.view.IWindow;
import android.view.InputDevice;
import android.view.PointerIcon;
import android.view.SurfaceControl;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
+import android.window.IUnhandledDragCallback;
+import android.window.IUnhandledDragListener;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.server.wm.WindowManagerInternal.IDragDropCallback;
import java.util.Objects;
@@ -59,6 +67,7 @@
static final int MSG_TEAR_DOWN_DRAG_AND_DROP_INPUT = 1;
static final int MSG_ANIMATION_END = 2;
static final int MSG_REMOVE_DRAG_SURFACE_TIMEOUT = 3;
+ static final int MSG_UNHANDLED_DROP_LISTENER_TIMEOUT = 4;
/**
* Drag state per operation.
@@ -72,6 +81,21 @@
private WindowManagerService mService;
private final Handler mHandler;
+ // The unhandled drag listener for handling cross-window drags that end with no target window
+ private IUnhandledDragListener mUnhandledDragListener;
+ private final IBinder.DeathRecipient mUnhandledDragListenerDeathRecipient =
+ new IBinder.DeathRecipient() {
+ @Override
+ public void binderDied() {
+ synchronized (mService.mGlobalLock) {
+ if (hasPendingUnhandledDropCallback()) {
+ onUnhandledDropCallback(false /* consumedByListeners */);
+ }
+ setUnhandledDragListener(null);
+ }
+ }
+ };
+
/**
* Callback which is used to sync drag state with the vendor-specific code.
*/
@@ -83,10 +107,16 @@
mHandler = new DragHandler(service, looper);
}
+ @VisibleForTesting
+ Handler getHandler() {
+ return mHandler;
+ }
+
boolean dragDropActiveLocked() {
return mDragState != null && !mDragState.isClosing();
}
+ @VisibleForTesting
boolean dragSurfaceRelinquishedToDropTarget() {
return mDragState != null && mDragState.mRelinquishDragSurfaceToDropTarget;
}
@@ -96,6 +126,32 @@
mCallback.set(callback);
}
+ /**
+ * Sets the listener for unhandled cross-window drags.
+ */
+ public void setUnhandledDragListener(IUnhandledDragListener listener) {
+ if (mUnhandledDragListener != null && mUnhandledDragListener.asBinder() != null) {
+ mUnhandledDragListener.asBinder().unlinkToDeath(
+ mUnhandledDragListenerDeathRecipient, 0);
+ }
+ mUnhandledDragListener = listener;
+ if (listener != null && listener.asBinder() != null) {
+ try {
+ mUnhandledDragListener.asBinder().linkToDeath(
+ mUnhandledDragListenerDeathRecipient, 0);
+ } catch (RemoteException e) {
+ mUnhandledDragListener = null;
+ }
+ }
+ }
+
+ /**
+ * Returns whether there is an unhandled drag listener set.
+ */
+ boolean hasUnhandledDragListener() {
+ return mUnhandledDragListener != null;
+ }
+
void sendDragStartedIfNeededLocked(WindowState window) {
mDragState.sendDragStartedIfNeededLocked(window);
}
@@ -247,6 +303,10 @@
}
}
+ /**
+ * This is called from the drop target window that received ACTION_DROP
+ * (see DragState#reportDropWindowLock()).
+ */
void reportDropResult(IWindow window, boolean consumed) {
IBinder token = window.asBinder();
if (DEBUG_DRAG) {
@@ -273,22 +333,89 @@
// so be sure to halt the timeout even if the later WindowState
// lookup fails.
mHandler.removeMessages(MSG_DRAG_END_TIMEOUT, window.asBinder());
+
WindowState callingWin = mService.windowForClientLocked(null, window, false);
if (callingWin == null) {
Slog.w(TAG_WM, "Bad result-reporting window " + window);
return; // !!! TODO: throw here?
}
- mDragState.mDragResult = consumed;
- mDragState.mRelinquishDragSurfaceToDropTarget = consumed
- && mDragState.targetInterceptsGlobalDrag(callingWin);
- mDragState.endDragLocked();
+ // If the drop was not consumed by the target window, then check if it should be
+ // consumed by the system unhandled drag listener
+ if (!consumed && notifyUnhandledDrop(mDragState.mUnhandledDropEvent,
+ "window-drop")) {
+ // If the unhandled drag listener is notified, then defer ending the drag until
+ // the listener calls back
+ return;
+ }
+
+ final boolean relinquishDragSurfaceToDropTarget =
+ consumed && mDragState.targetInterceptsGlobalDrag(callingWin);
+ mDragState.endDragLocked(consumed, relinquishDragSurfaceToDropTarget);
}
} finally {
mCallback.get().postReportDropResult();
}
}
+ /**
+ * Notifies the unhandled drag listener if needed.
+ * @return whether the listener was notified and subsequent drag completion should be deferred
+ * until the listener calls back
+ */
+ boolean notifyUnhandledDrop(DragEvent dropEvent, String reason) {
+ final boolean isLocalDrag =
+ (mDragState.mFlags & (DRAG_FLAG_GLOBAL_SAME_APPLICATION | DRAG_FLAG_GLOBAL)) == 0;
+ if (!com.android.window.flags.Flags.delegateUnhandledDrags()
+ || mUnhandledDragListener == null
+ || isLocalDrag) {
+ // Skip if the flag is disabled, there is no unhandled-drag listener, or if this is a
+ // purely local drag
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Skipping unhandled listener "
+ + "(listener=" + mUnhandledDragListener + ", flags=" + mDragState.mFlags + ")");
+ return false;
+ }
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Sending DROP to unhandled listener (" + reason + ")");
+ try {
+ // Schedule timeout for the unhandled drag listener to call back
+ sendTimeoutMessage(MSG_UNHANDLED_DROP_LISTENER_TIMEOUT, null, DRAG_TIMEOUT_MS);
+ mUnhandledDragListener.onUnhandledDrop(dropEvent, new IUnhandledDragCallback.Stub() {
+ @Override
+ public void notifyUnhandledDropComplete(boolean consumedByListener) {
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Unhandled listener finished handling DROP");
+ synchronized (mService.mGlobalLock) {
+ onUnhandledDropCallback(consumedByListener);
+ }
+ }
+ });
+ return true;
+ } catch (RemoteException e) {
+ Slog.e(TAG_WM, "Failed to call unhandled drag listener", e);
+ return false;
+ }
+ }
+
+ /**
+ * Called when the unhandled drag listener has completed handling the drop
+ * (if it was notififed).
+ */
+ @VisibleForTesting
+ void onUnhandledDropCallback(boolean consumedByListener) {
+ mHandler.removeMessages(MSG_UNHANDLED_DROP_LISTENER_TIMEOUT, null);
+ // If handled, then the listeners assume responsibility of cleaning up the drag surface
+ mDragState.mDragResult = consumedByListener;
+ mDragState.mRelinquishDragSurfaceToDropTarget = consumedByListener;
+ mDragState.closeLocked();
+ }
+
+ /**
+ * Returns whether we are currently waiting for the unhandled drag listener to callback after
+ * it was notified of an unhandled drag.
+ */
+ boolean hasPendingUnhandledDropCallback() {
+ return mHandler.hasMessages(MSG_UNHANDLED_DROP_LISTENER_TIMEOUT);
+ }
+
void cancelDragAndDrop(IBinder dragToken, boolean skipAnimation) {
if (DEBUG_DRAG) {
Slog.d(TAG_WM, "cancelDragAndDrop");
@@ -436,8 +563,8 @@
synchronized (mService.mGlobalLock) {
// !!! TODO: ANR the drag-receiving app
if (mDragState != null) {
- mDragState.mDragResult = false;
- mDragState.endDragLocked();
+ mDragState.endDragLocked(false /* consumed */,
+ false /* relinquishDragSurfaceToDropTarget */);
}
}
break;
@@ -473,6 +600,13 @@
}
break;
}
+
+ case MSG_UNHANDLED_DROP_LISTENER_TIMEOUT: {
+ synchronized (mService.mGlobalLock) {
+ onUnhandledDropCallback(false /* consumedByListener */);
+ }
+ break;
+ }
}
}
}
diff --git a/services/core/java/com/android/server/wm/DragState.java b/services/core/java/com/android/server/wm/DragState.java
index d302f06..76038b9 100644
--- a/services/core/java/com/android/server/wm/DragState.java
+++ b/services/core/java/com/android/server/wm/DragState.java
@@ -147,6 +147,11 @@
*/
private boolean mIsClosing;
+ // Stores the last drop event which was reported to a valid drop target window, or null
+ // otherwise. This drop event will contain private info and should only be consumed by the
+ // unhandled drag listener.
+ DragEvent mUnhandledDropEvent;
+
DragState(WindowManagerService service, DragDropController controller, IBinder token,
SurfaceControl surface, int flags, IBinder localWin) {
mService = service;
@@ -287,14 +292,54 @@
mData = null;
mThumbOffsetX = mThumbOffsetY = 0;
mNotifiedWindows = null;
+ if (mUnhandledDropEvent != null) {
+ mUnhandledDropEvent.recycle();
+ mUnhandledDropEvent = null;
+ }
// Notifies the controller that the drag state is closed.
mDragDropController.onDragStateClosedLocked(this);
}
/**
+ * Creates the drop event for this drag gesture. If `touchedWin` is null, then the drop event
+ * will be created for dispatching to the unhandled drag and the drag surface will be provided
+ * as a part of the dispatched event.
+ */
+ private DragEvent createDropEvent(float x, float y, @Nullable WindowState touchedWin,
+ boolean includeDragSurface) {
+ if (touchedWin != null) {
+ final int targetUserId = UserHandle.getUserId(touchedWin.getOwningUid());
+ final DragAndDropPermissionsHandler dragAndDropPermissions;
+ if ((mFlags & View.DRAG_FLAG_GLOBAL) != 0 && (mFlags & DRAG_FLAGS_URI_ACCESS) != 0
+ && mData != null) {
+ dragAndDropPermissions = new DragAndDropPermissionsHandler(mService.mGlobalLock,
+ mData,
+ mUid,
+ touchedWin.getOwningPackage(),
+ mFlags & DRAG_FLAGS_URI_PERMISSIONS,
+ mSourceUserId,
+ targetUserId);
+ } else {
+ dragAndDropPermissions = null;
+ }
+ if (mSourceUserId != targetUserId) {
+ if (mData != null) {
+ mData.fixUris(mSourceUserId);
+ }
+ }
+ return obtainDragEvent(DragEvent.ACTION_DROP, x, y, mData,
+ targetInterceptsGlobalDrag(touchedWin), dragAndDropPermissions);
+ } else {
+ return obtainDragEvent(DragEvent.ACTION_DROP, x, y, mData,
+ includeDragSurface /* includeDragSurface */, null /* dragAndDropPermissions */);
+ }
+ }
+
+ /**
* Notify the drop target and tells it about the data. If the drop event is not sent to the
- * target, invokes {@code endDragLocked} immediately.
+ * target, invokes {@code endDragLocked} after the unhandled drag listener gets a chance to
+ * handle the drop.
*/
boolean reportDropWindowLock(IBinder token, float x, float y) {
if (mAnimator != null) {
@@ -302,41 +347,27 @@
}
final WindowState touchedWin = mService.mInputToWindowMap.get(token);
+ final DragEvent unhandledDropEvent = createDropEvent(x, y, null /* touchedWin */,
+ true /* includePrivateInfo */);
if (!isWindowNotified(touchedWin)) {
- // "drop" outside a valid window -- no recipient to apply a
- // timeout to, and we can send the drag-ended message immediately.
- mDragResult = false;
- endDragLocked();
+ // Delegate to the unhandled drag listener as a first pass
+ if (mDragDropController.notifyUnhandledDrop(unhandledDropEvent, "unhandled-drop")) {
+ // The unhandled drag listener will call back to notify whether it has consumed
+ // the drag, so return here
+ return true;
+ }
+
+ // "drop" outside a valid window -- no recipient to apply a timeout to, and we can send
+ // the drag-ended message immediately.
+ endDragLocked(false /* consumed */, false /* relinquishDragSurfaceToDropTarget */);
if (DEBUG_DRAG) Slog.d(TAG_WM, "Drop outside a valid window " + touchedWin);
return false;
}
if (DEBUG_DRAG) Slog.d(TAG_WM, "sending DROP to " + touchedWin);
- final int targetUserId = UserHandle.getUserId(touchedWin.getOwningUid());
-
- final DragAndDropPermissionsHandler dragAndDropPermissions;
- if ((mFlags & View.DRAG_FLAG_GLOBAL) != 0 && (mFlags & DRAG_FLAGS_URI_ACCESS) != 0
- && mData != null) {
- dragAndDropPermissions = new DragAndDropPermissionsHandler(mService.mGlobalLock,
- mData,
- mUid,
- touchedWin.getOwningPackage(),
- mFlags & DRAG_FLAGS_URI_PERMISSIONS,
- mSourceUserId,
- targetUserId);
- } else {
- dragAndDropPermissions = null;
- }
- if (mSourceUserId != targetUserId) {
- if (mData != null) {
- mData.fixUris(mSourceUserId);
- }
- }
final IBinder clientToken = touchedWin.mClient.asBinder();
- final DragEvent event = obtainDragEvent(DragEvent.ACTION_DROP, x, y,
- mData, targetInterceptsGlobalDrag(touchedWin),
- dragAndDropPermissions);
+ final DragEvent event = createDropEvent(x, y, touchedWin, false /* includePrivateInfo */);
try {
touchedWin.mClient.dispatchDragEvent(event);
@@ -345,7 +376,7 @@
DragDropController.DRAG_TIMEOUT_MS);
} catch (RemoteException e) {
Slog.w(TAG_WM, "can't send drop notification to win " + touchedWin);
- endDragLocked();
+ endDragLocked(false /* consumed */, false /* relinquishDragSurfaceToDropTarget */);
return false;
} finally {
if (MY_PID != touchedWin.mSession.mPid) {
@@ -353,6 +384,7 @@
}
}
mToken = clientToken;
+ mUnhandledDropEvent = unhandledDropEvent;
return true;
}
@@ -478,6 +510,9 @@
boolean containsAppExtras) {
final boolean interceptsGlobalDrag = targetInterceptsGlobalDrag(newWin);
if (mDragInProgress && isValidDropTarget(newWin, containsAppExtras, interceptsGlobalDrag)) {
+ if (DEBUG_DRAG) {
+ Slog.d(TAG_WM, "Sending DRAG_STARTED to new window " + newWin);
+ }
// Only allow the extras to be dispatched to a global-intercepting drag target
ClipData data = interceptsGlobalDrag ? mData.copyForTransferWithActivityInfo() : null;
DragEvent event = obtainDragEvent(DragEvent.ACTION_DRAG_STARTED,
@@ -523,14 +558,25 @@
return false;
}
if (!targetWin.isPotentialDragTarget(interceptsGlobalDrag)) {
+ // Window should not be a target
return false;
}
- if ((mFlags & View.DRAG_FLAG_GLOBAL) == 0 || !targetWindowSupportsGlobalDrag(targetWin)) {
+ final boolean isGlobalSameAppDrag = (mFlags & View.DRAG_FLAG_GLOBAL_SAME_APPLICATION) != 0;
+ final boolean isGlobalDrag = (mFlags & View.DRAG_FLAG_GLOBAL) != 0;
+ final boolean isAnyGlobalDrag = isGlobalDrag || isGlobalSameAppDrag;
+ if (!isAnyGlobalDrag || !targetWindowSupportsGlobalDrag(targetWin)) {
// Drag is limited to the current window.
if (!isLocalWindow) {
return false;
}
}
+ if (isGlobalSameAppDrag) {
+ // Drag is limited to app windows from the same uid or windows that can intercept global
+ // drag
+ if (!interceptsGlobalDrag && mUid != targetWin.getUid()) {
+ return false;
+ }
+ }
return interceptsGlobalDrag
|| mCrossProfileCopyAllowed
@@ -547,7 +593,10 @@
/**
* @return whether the given window {@param targetWin} can intercept global drags.
*/
- public boolean targetInterceptsGlobalDrag(WindowState targetWin) {
+ public boolean targetInterceptsGlobalDrag(@Nullable WindowState targetWin) {
+ if (targetWin == null) {
+ return false;
+ }
return (targetWin.mAttrs.privateFlags & PRIVATE_FLAG_INTERCEPT_GLOBAL_DRAG_AND_DROP) != 0;
}
@@ -561,9 +610,6 @@
if (isWindowNotified(newWin)) {
return;
}
- if (DEBUG_DRAG) {
- Slog.d(TAG_WM, "need to send DRAG_STARTED to new window " + newWin);
- }
sendDragStartedLocked(newWin, mCurrentX, mCurrentY,
containsApplicationExtras(mDataDescription));
}
@@ -578,7 +624,13 @@
return false;
}
- void endDragLocked() {
+ /**
+ * Ends the current drag, animating the drag surface back to the source if the drop was not
+ * consumed by the receiving window.
+ */
+ void endDragLocked(boolean dropConsumed, boolean relinquishDragSurfaceToDropTarget) {
+ mDragResult = dropConsumed;
+ mRelinquishDragSurfaceToDropTarget = relinquishDragSurfaceToDropTarget;
if (mAnimator != null) {
return;
}
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 4ea76e1..de8d9f9 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -310,6 +310,7 @@
import android.window.ISurfaceSyncGroupCompletedListener;
import android.window.ITaskFpsCallback;
import android.window.ITrustedPresentationListener;
+import android.window.IUnhandledDragListener;
import android.window.InputTransferToken;
import android.window.ScreenCapture;
import android.window.SystemPerformanceHinter;
@@ -10026,4 +10027,16 @@
void onProcessActivityVisibilityChanged(int uid, boolean visible) {
mScreenRecordingCallbackController.onProcessActivityVisibilityChanged(uid, visible);
}
+
+ /**
+ * Sets the listener to be called back when a cross-window drag and drop operation is unhandled
+ * (ie. not handled by any window which can handle the drag).
+ */
+ @Override
+ public void setUnhandledDragListener(IUnhandledDragListener listener) throws RemoteException {
+ mAtmService.enforceTaskPermission("setUnhandledDragListener");
+ synchronized (mGlobalLock) {
+ mDragDropController.setUnhandledDragListener(listener);
+ }
+ }
}
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index dfa9dce..3607ddd 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -34,6 +34,7 @@
"tvinput/BufferProducerThread.cpp",
"tvinput/JTvInputHal.cpp",
"tvinput/TvInputHal_hidl.cpp",
+ "com_android_server_accessibility_BrailleDisplayConnection.cpp",
"com_android_server_adb_AdbDebuggingManager.cpp",
"com_android_server_am_BatteryStatsService.cpp",
"com_android_server_biometrics_SurfaceToNativeHandleConverter.cpp",
diff --git a/services/core/jni/OWNERS b/services/core/jni/OWNERS
index df7fb99..b999305f 100644
--- a/services/core/jni/OWNERS
+++ b/services/core/jni/OWNERS
@@ -15,6 +15,7 @@
per-file com_android_server_SystemClock* = file:/services/core/java/com/android/server/timedetector/OWNERS
per-file com_android_server_Usb* = file:/services/usb/OWNERS
per-file com_android_server_Vibrator* = file:/services/core/java/com/android/server/vibrator/OWNERS
+per-file com_android_server_accessibility_* = file:/services/accessibility/OWNERS
per-file com_android_server_hdmi_* = file:/core/java/android/hardware/hdmi/OWNERS
per-file com_android_server_lights_* = file:/services/core/java/com/android/server/lights/OWNERS
per-file com_android_server_location_* = file:/location/java/android/location/OWNERS
diff --git a/services/core/jni/com_android_server_accessibility_BrailleDisplayConnection.cpp b/services/core/jni/com_android_server_accessibility_BrailleDisplayConnection.cpp
new file mode 100644
index 0000000..9a509a7
--- /dev/null
+++ b/services/core/jni/com_android_server_accessibility_BrailleDisplayConnection.cpp
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <core_jni_helpers.h>
+#include <jni.h>
+#include <linux/hidraw.h>
+#include <linux/input.h>
+#include <nativehelper/JNIHelp.h>
+#include <sys/ioctl.h>
+
+/*
+ * This file defines simple wrappers around the kernel UAPI HIDRAW driver's ioctl() commands.
+ * See kernel example samples/hidraw/hid-example.c
+ *
+ * All methods expect an open file descriptor int from Java.
+ */
+
+namespace android {
+
+namespace {
+
+// Max size we allow for the result from HIDIOCGRAWUNIQ (Bluetooth address or USB serial number).
+// Copied from linux/hid.h struct hid_device->uniq char array size; the ioctl implementation
+// writes at most this many bytes to the provided buffer.
+constexpr int UNIQ_SIZE_MAX = 64;
+
+} // anonymous namespace
+
+static jint com_android_server_accessibility_BrailleDisplayConnection_getHidrawDescSize(
+ JNIEnv* env, jobject thiz, int fd) {
+ int size = 0;
+ if (ioctl(fd, HIDIOCGRDESCSIZE, &size) < 0) {
+ return -1;
+ }
+ return size;
+}
+
+static jbyteArray com_android_server_accessibility_BrailleDisplayConnection_getHidrawDesc(
+ JNIEnv* env, jobject thiz, int fd, int descSize) {
+ struct hidraw_report_descriptor desc;
+ desc.size = descSize;
+ if (ioctl(fd, HIDIOCGRDESC, &desc) < 0) {
+ return nullptr;
+ }
+ jbyteArray result = env->NewByteArray(descSize);
+ if (result != nullptr) {
+ env->SetByteArrayRegion(result, 0, descSize, (jbyte*)desc.value);
+ }
+ // Local ref is not deleted because it is returned to Java
+ return result;
+}
+
+static jstring com_android_server_accessibility_BrailleDisplayConnection_getHidrawUniq(JNIEnv* env,
+ jobject thiz,
+ int fd) {
+ char buf[UNIQ_SIZE_MAX];
+ if (ioctl(fd, HIDIOCGRAWUNIQ(UNIQ_SIZE_MAX), buf) < 0) {
+ return nullptr;
+ }
+ // Local ref is not deleted because it is returned to Java
+ return env->NewStringUTF(buf);
+}
+
+static jint com_android_server_accessibility_BrailleDisplayConnection_getHidrawBusType(JNIEnv* env,
+ jobject thiz,
+ int fd) {
+ struct hidraw_devinfo info;
+ if (ioctl(fd, HIDIOCGRAWINFO, &info) < 0) {
+ return -1;
+ }
+ return info.bustype;
+}
+
+static const JNINativeMethod gMethods[] = {
+ {"nativeGetHidrawDescSize", "(I)I",
+ (void*)com_android_server_accessibility_BrailleDisplayConnection_getHidrawDescSize},
+ {"nativeGetHidrawDesc", "(II)[B",
+ (void*)com_android_server_accessibility_BrailleDisplayConnection_getHidrawDesc},
+ {"nativeGetHidrawUniq", "(I)Ljava/lang/String;",
+ (void*)com_android_server_accessibility_BrailleDisplayConnection_getHidrawUniq},
+ {"nativeGetHidrawBusType", "(I)I",
+ (void*)com_android_server_accessibility_BrailleDisplayConnection_getHidrawBusType},
+};
+
+int register_com_android_server_accessibility_BrailleDisplayConnection(JNIEnv* env) {
+ return RegisterMethodsOrDie(env, "com/android/server/accessibility/BrailleDisplayConnection",
+ gMethods, NELEM(gMethods));
+}
+
+}; // namespace android
diff --git a/services/core/jni/onload.cpp b/services/core/jni/onload.cpp
index 5d1eb49..0936888 100644
--- a/services/core/jni/onload.cpp
+++ b/services/core/jni/onload.cpp
@@ -70,6 +70,7 @@
int register_com_android_server_display_DisplayControl(JNIEnv* env);
int register_com_android_server_SystemClockTime(JNIEnv* env);
int register_android_server_display_smallAreaDetectionController(JNIEnv* env);
+int register_com_android_server_accessibility_BrailleDisplayConnection(JNIEnv* env);
};
using namespace android;
@@ -132,5 +133,6 @@
register_com_android_server_display_DisplayControl(env);
register_com_android_server_SystemClockTime(env);
register_android_server_display_smallAreaDetectionController(env);
+ register_com_android_server_accessibility_BrailleDisplayConnection(env);
return JNI_VERSION_1_4;
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 05d1c49..85eac29 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -98,6 +98,7 @@
import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS;
import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION;
import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_AFFILIATED;
+import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_FORCE_LOCK;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_WIPE_DATA;
import static android.app.admin.DeviceAdminReceiver.ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED;
@@ -189,6 +190,7 @@
import static android.app.admin.DevicePolicyManager.STATUS_MANAGED_USERS_NOT_SUPPORTED;
import static android.app.admin.DevicePolicyManager.STATUS_NONSYSTEM_USER_EXISTS;
import static android.app.admin.DevicePolicyManager.STATUS_NOT_SYSTEM_USER;
+import static android.app.admin.DevicePolicyManager.STATUS_HEADLESS_ONLY_SYSTEM_USER;
import static android.app.admin.DevicePolicyManager.STATUS_OK;
import static android.app.admin.DevicePolicyManager.STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
import static android.app.admin.DevicePolicyManager.STATUS_SYSTEM_USER;
@@ -225,6 +227,7 @@
import static android.app.admin.ProvisioningException.ERROR_STARTING_PROFILE_FAILED;
import static android.app.admin.flags.Flags.backupServiceSecurityLogEventEnabled;
import static android.app.admin.flags.Flags.dumpsysPolicyEngineMigrationEnabled;
+import static android.app.admin.flags.Flags.headlessDeviceOwnerSingleUserEnabled;
import static android.app.admin.flags.Flags.policyEngineMigrationV2Enabled;
import static android.content.Intent.ACTION_MANAGED_PROFILE_AVAILABLE;
import static android.content.Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE;
@@ -9460,7 +9463,8 @@
}
if (setProfileOwnerOnCurrentUserIfNecessary
- && mInjector.userManagerIsHeadlessSystemUserMode()) {
+ && mInjector.userManagerIsHeadlessSystemUserMode()
+ && getHeadlessDeviceOwnerMode() == HEADLESS_DEVICE_OWNER_MODE_AFFILIATED) {
int currentForegroundUser;
synchronized (getLockObject()) {
currentForegroundUser = getCurrentForegroundUserId();
@@ -9476,6 +9480,12 @@
return true;
}
+ private int getHeadlessDeviceOwnerMode() {
+ synchronized (getLockObject()) {
+ return getDeviceOwnerAdminLocked().info.getHeadlessDeviceOwnerMode();
+ }
+ }
+
/**
* This API is cached: invalidate with invalidateBinderCaches().
*/
@@ -12226,6 +12236,13 @@
+ admin + " are not in the same package");
}
final CallerIdentity caller = getCallerIdentity(admin);
+
+ if (headlessDeviceOwnerSingleUserEnabled()) {
+ // Block this method if the device is in headless main user mode
+ Preconditions.checkCallAuthorization(
+ getHeadlessDeviceOwnerMode() != HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER,
+ "createAndManageUser was called while in headless single user mode");
+ }
// Only allow the system user to use this method
Preconditions.checkCallAuthorization(caller.getUserHandle().isSystem(),
"createAndManageUser was called from non-system user");
@@ -16636,29 +16653,51 @@
return STATUS_USER_NOT_RUNNING;
}
+ DeviceAdminInfo adminInfo = null;
+
+ boolean isHeadlessModeAffiliated = false;
+
+ boolean isHeadlessModeSingleUser = false;
+
boolean isHeadlessSystemUserMode = mInjector.userManagerIsHeadlessSystemUserMode();
+ int ensureSetUpUser = UserHandle.USER_SYSTEM;
if (isHeadlessSystemUserMode) {
- if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
+ if (owner != null) {
+ adminInfo = findAdmin(owner,
+ deviceOwnerUserId, /* throwForMissingPermission= */ false);
+
+ isHeadlessModeAffiliated =
+ adminInfo.getHeadlessDeviceOwnerMode()
+ == HEADLESS_DEVICE_OWNER_MODE_AFFILIATED;
+
+ isHeadlessModeSingleUser =
+ adminInfo.getHeadlessDeviceOwnerMode()
+ == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER;
+
+ if (!isHeadlessModeAffiliated && !isHeadlessModeSingleUser) {
+ return STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
+ }
+
+ if (headlessDeviceOwnerSingleUserEnabled() && isHeadlessModeSingleUser) {
+ ensureSetUpUser = mUserManagerInternal.getMainUserId();
+ if (ensureSetUpUser == UserHandle.USER_NULL) {
+ return STATUS_HEADLESS_ONLY_SYSTEM_USER;
+ }
+ }
+ }
+
+ if (isHeadlessModeAffiliated && deviceOwnerUserId != UserHandle.USER_SYSTEM) {
Slogf.e(LOG_TAG, "In headless system user mode, "
+ "device owner can only be set on headless system user.");
return STATUS_NOT_SYSTEM_USER;
}
- if (owner != null) {
- DeviceAdminInfo adminInfo = findAdmin(
- owner, deviceOwnerUserId, /* throwForMissingPermission= */ false);
-
- if (adminInfo.getHeadlessDeviceOwnerMode()
- != HEADLESS_DEVICE_OWNER_MODE_AFFILIATED) {
- return STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
- }
- }
}
if (isAdb) {
// If shell command runs after user setup completed check device status. Otherwise, OK.
- if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
+ if (hasUserSetupCompleted(ensureSetUpUser)) {
// DO can be setup only if there are no users which are neither created by default
// nor marked as FOR_TESTING
@@ -16681,11 +16720,12 @@
return STATUS_OK;
} else {
// DO has to be user 0
- if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
+ if ((!isHeadlessSystemUserMode || isHeadlessModeAffiliated)
+ && deviceOwnerUserId != UserHandle.USER_SYSTEM) {
return STATUS_NOT_SYSTEM_USER;
}
// Only provision DO before setup wizard completes
- if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
+ if (hasUserSetupCompleted(ensureSetUpUser)) {
return STATUS_USER_SETUP_COMPLETED;
}
return STATUS_OK;
@@ -21260,7 +21300,11 @@
setTimeAndTimezone(provisioningParams.getTimeZone(), provisioningParams.getLocalTime());
setLocale(provisioningParams.getLocale());
- int deviceOwnerUserId = UserHandle.USER_SYSTEM;
+ int deviceOwnerUserId = headlessDeviceOwnerSingleUserEnabled()
+ && getHeadlessDeviceOwnerMode() == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER
+ ? mUserManagerInternal.getMainUserId()
+ : UserHandle.USER_SYSTEM;
+
if (!removeNonRequiredAppsForManagedDevice(
deviceOwnerUserId,
provisioningParams.isLeaveAllSystemAppsEnabled(),
diff --git a/services/foldables/devicestateprovider/src/com/android/server/policy/BookStyleDeviceStatePolicy.java b/services/foldables/devicestateprovider/src/com/android/server/policy/BookStyleDeviceStatePolicy.java
index 8b22718..bc264a4 100644
--- a/services/foldables/devicestateprovider/src/com/android/server/policy/BookStyleDeviceStatePolicy.java
+++ b/services/foldables/devicestateprovider/src/com/android/server/policy/BookStyleDeviceStatePolicy.java
@@ -16,11 +16,12 @@
package com.android.server.policy;
-import static com.android.server.devicestate.DeviceState.FLAG_CANCEL_OVERRIDE_REQUESTS;
-import static com.android.server.devicestate.DeviceState.FLAG_CANCEL_WHEN_REQUESTER_NOT_ON_TOP;
-import static com.android.server.devicestate.DeviceState.FLAG_EMULATED_ONLY;
-import static com.android.server.devicestate.DeviceState.FLAG_UNSUPPORTED_WHEN_POWER_SAVE_MODE;
-import static com.android.server.devicestate.DeviceState.FLAG_UNSUPPORTED_WHEN_THERMAL_STATUS_CRITICAL;
+import static android.hardware.devicestate.DeviceState.FLAG_CANCEL_OVERRIDE_REQUESTS;
+import static android.hardware.devicestate.DeviceState.FLAG_CANCEL_WHEN_REQUESTER_NOT_ON_TOP;
+import static android.hardware.devicestate.DeviceState.FLAG_EMULATED_ONLY;
+import static android.hardware.devicestate.DeviceState.FLAG_UNSUPPORTED_WHEN_POWER_SAVE_MODE;
+import static android.hardware.devicestate.DeviceState.FLAG_UNSUPPORTED_WHEN_THERMAL_STATUS_CRITICAL;
+
import static com.android.server.policy.BookStyleStateTransitions.DEFAULT_STATE_TRANSITIONS;
import static com.android.server.policy.FoldableDeviceStateProvider.DeviceStateConfiguration.createConfig;
import static com.android.server.policy.FoldableDeviceStateProvider.DeviceStateConfiguration.createTentModeClosedState;
@@ -36,7 +37,6 @@
import com.android.server.devicestate.DeviceStateProvider;
import com.android.server.policy.FoldableDeviceStateProvider.DeviceStateConfiguration;
import com.android.server.policy.feature.flags.FeatureFlags;
-import com.android.server.policy.feature.flags.FeatureFlagsImpl;
import java.io.PrintWriter;
import java.util.function.Predicate;
diff --git a/services/foldables/devicestateprovider/src/com/android/server/policy/FoldableDeviceStateProvider.java b/services/foldables/devicestateprovider/src/com/android/server/policy/FoldableDeviceStateProvider.java
index 021a667..bf2619b 100644
--- a/services/foldables/devicestateprovider/src/com/android/server/policy/FoldableDeviceStateProvider.java
+++ b/services/foldables/devicestateprovider/src/com/android/server/policy/FoldableDeviceStateProvider.java
@@ -34,6 +34,7 @@
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
+import android.hardware.devicestate.DeviceState;
import android.hardware.display.DisplayManager;
import android.os.Handler;
import android.os.Looper;
@@ -48,7 +49,6 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
-import com.android.server.devicestate.DeviceState;
import com.android.server.devicestate.DeviceStateProvider;
import com.android.server.policy.feature.flags.FeatureFlags;
import com.android.server.policy.feature.flags.FeatureFlagsImpl;
diff --git a/services/foldables/devicestateprovider/tests/src/com/android/server/policy/FoldableDeviceStateProviderTest.java b/services/foldables/devicestateprovider/tests/src/com/android/server/policy/FoldableDeviceStateProviderTest.java
index 04cebab..930f4a6 100644
--- a/services/foldables/devicestateprovider/tests/src/com/android/server/policy/FoldableDeviceStateProviderTest.java
+++ b/services/foldables/devicestateprovider/tests/src/com/android/server/policy/FoldableDeviceStateProviderTest.java
@@ -51,6 +51,7 @@
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
+import android.hardware.devicestate.DeviceState;
import android.hardware.display.DisplayManager;
import android.hardware.input.InputSensorInfo;
import android.os.Handler;
@@ -58,7 +59,6 @@
import android.testing.AndroidTestingRunner;
import android.view.Display;
-import com.android.server.devicestate.DeviceState;
import com.android.server.devicestate.DeviceStateProvider.Listener;
import com.android.server.policy.FoldableDeviceStateProvider.DeviceStateConfiguration;
import com.android.server.policy.feature.flags.FakeFeatureFlagsImpl;
diff --git a/services/people/java/com/android/server/people/PeopleService.java b/services/people/java/com/android/server/people/PeopleService.java
index 885ed35..b9f00d7 100644
--- a/services/people/java/com/android/server/people/PeopleService.java
+++ b/services/people/java/com/android/server/people/PeopleService.java
@@ -38,6 +38,7 @@
import android.os.Binder;
import android.os.CancellationSignal;
import android.os.IBinder;
+import android.os.IRemoteCallback;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
@@ -474,6 +475,10 @@
getDataManager().restore(userId, payload);
}
+ @Override
+ public void requestServiceFeatures(AppPredictionSessionId sessionId,
+ IRemoteCallback callback) {}
+
@VisibleForTesting
SessionInfo getSessionInfo(AppPredictionSessionId sessionId) {
return mSessions.get(sessionId);
diff --git a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationManagerApiTest.kt b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationManagerApiTest.kt
index a8100af..66e0717 100644
--- a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationManagerApiTest.kt
+++ b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationManagerApiTest.kt
@@ -18,6 +18,10 @@
import android.content.Context
import android.content.Intent
+import android.content.UriRelativeFilter
+import android.content.UriRelativeFilterGroup
+import android.content.UriRelativeFilterGroupParcel
+import android.content.pm.Flags
import android.content.pm.PackageManager
import android.content.pm.verify.domain.DomainOwner
import android.content.pm.verify.domain.DomainVerificationInfo
@@ -25,8 +29,10 @@
import android.content.pm.verify.domain.DomainVerificationUserState
import android.content.pm.verify.domain.IDomainVerificationManager
import android.os.Build
-import android.os.PatternMatcher
+import android.os.Bundle
+import android.os.PatternMatcher.PATTERN_LITERAL
import android.os.Process
+import android.platform.test.annotations.RequiresFlagsEnabled
import android.util.ArraySet
import android.util.SparseArray
import com.android.internal.pm.parsing.pkg.AndroidPackageInternal
@@ -68,6 +74,63 @@
private val DOMAIN_4 = "four.$DOMAIN_BASE"
}
+ @RequiresFlagsEnabled(Flags.FLAG_RELATIVE_REFERENCE_INTENT_FILTERS)
+ @Test
+ fun updateUriRelativeFilterGroups() {
+ val pkgWithDomains = mockPkgState(PKG_ONE, UUID_ONE, listOf(DOMAIN_1, DOMAIN_2))
+ val service = makeService(pkgWithDomains).apply {
+ addPackages(pkgWithDomains)
+ }
+
+ val bundle = service.getUriRelativeFilterGroups(PKG_ONE, listOf(DOMAIN_1, DOMAIN_2))
+ assertThat(bundle.keySet()).containsExactlyElementsIn(listOf(DOMAIN_1, DOMAIN_2))
+ assertThat(bundle.getParcelableArrayList(DOMAIN_1, UriRelativeFilterGroup::class.java))
+ .isEmpty()
+ assertThat(bundle.getParcelableArrayList(DOMAIN_2, UriRelativeFilterGroup::class.java))
+ .isEmpty()
+
+ val pathGroup = UriRelativeFilterGroup(UriRelativeFilterGroup.ACTION_ALLOW)
+ pathGroup.addUriRelativeFilter(
+ UriRelativeFilter(UriRelativeFilter.PATH, PATTERN_LITERAL, "path")
+ )
+ val queryGroup = UriRelativeFilterGroup(UriRelativeFilterGroup.ACTION_BLOCK)
+ queryGroup.addUriRelativeFilter(
+ UriRelativeFilter(UriRelativeFilter.QUERY, PATTERN_LITERAL, "query")
+ )
+ val fragmentGroup = UriRelativeFilterGroup(UriRelativeFilterGroup.ACTION_ALLOW)
+ fragmentGroup.addUriRelativeFilter(
+ UriRelativeFilter(UriRelativeFilter.FRAGMENT, PATTERN_LITERAL, "fragment")
+ )
+
+ assertGroups(service, arrayListOf(pathGroup))
+ assertGroups(service, arrayListOf(queryGroup, pathGroup))
+ assertGroups(service, arrayListOf(queryGroup, fragmentGroup, pathGroup))
+ }
+
+ private fun assertGroups(
+ service: DomainVerificationService,
+ groups: List<UriRelativeFilterGroup>
+ ) {
+ val bundle = Bundle()
+ bundle.putParcelableList(DOMAIN_1, UriRelativeFilterGroup.groupsToParcels(groups))
+ service.setUriRelativeFilterGroups(PKG_ONE, bundle)
+ val fetchedBundle = service.getUriRelativeFilterGroups(PKG_ONE, listOf(DOMAIN_1))
+ assertThat(fetchedBundle.keySet()).containsExactlyElementsIn(bundle.keySet())
+ assertThat(
+ UriRelativeFilterGroup.parcelsToGroups(
+ fetchedBundle.getParcelableArrayList(
+ DOMAIN_1,
+ UriRelativeFilterGroupParcel::class.java)
+ )
+ ).containsExactlyElementsIn(
+ UriRelativeFilterGroup.parcelsToGroups(
+ bundle.getParcelableArrayList(
+ DOMAIN_1,
+ UriRelativeFilterGroupParcel::class.java)
+ )
+ ).inOrder()
+ }
+
@Test
fun queryValidVerificationPackageNames() {
val pkgWithDomains = mockPkgState(PKG_ONE, UUID_ONE, listOf(DOMAIN_1, DOMAIN_2))
@@ -484,6 +547,7 @@
DomainVerificationService(mockThrowOnUnmocked {
// Assume the test has every permission necessary
whenever(enforcePermission(anyString(), anyInt(), anyInt(), anyString()))
+ whenever(enforceCallingOrSelfPermission(anyString(), anyString()))
whenever(checkPermission(anyString(), anyInt(), anyInt())) {
PackageManager.PERMISSION_GRANTED
}
@@ -539,7 +603,7 @@
addCategory(Intent.CATEGORY_DEFAULT)
addDataScheme("http")
addDataScheme("https")
- addDataPath("/sub", PatternMatcher.PATTERN_LITERAL)
+ addDataPath("/sub", PATTERN_LITERAL)
addDataAuthority(it, null)
}
}
diff --git a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationPersistenceTest.kt b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationPersistenceTest.kt
index 65b99c5..4fa4190 100644
--- a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationPersistenceTest.kt
+++ b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/verify/domain/DomainVerificationPersistenceTest.kt
@@ -16,7 +16,12 @@
package com.android.server.pm.test.verify.domain
+import android.content.UriRelativeFilter
+import android.content.UriRelativeFilter.PATH
+import android.content.UriRelativeFilterGroup
+import android.content.UriRelativeFilterGroup.ACTION_ALLOW
import android.content.pm.verify.domain.DomainVerificationState
+import android.os.PatternMatcher.PATTERN_LITERAL
import android.os.UserHandle
import android.util.ArrayMap
import android.util.SparseArray
@@ -157,7 +162,7 @@
@Test
fun writeStateSignatureIfFunctionReturnsNull() {
- val (attached, pending, restored) = mockWriteValues { "SIGNATURE_$it" }
+ val (attached, pending, restored) = mockWriteValues { "SIGNATURE_$it" }
val file = tempFolder.newFile().writeXml {
DomainVerificationPersistence.writeToXml(it, attached, pending, restored,
UserHandle.USER_ALL) { null }
@@ -313,6 +318,9 @@
addHosts(setOf("$packageName-user.com"))
isLinkHandlingAllowed = true
}
+ val group = UriRelativeFilterGroup(ACTION_ALLOW)
+ group.addUriRelativeFilter(UriRelativeFilter(PATH, PATTERN_LITERAL, "test"))
+ uriRelativeFilterGroupMap.put("example.com", listOf(group))
}
private fun pkgName(id: Int) = "$PKG_PREFIX.pkg$id"
diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java
index 28471b3..6bcd778 100644
--- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java
@@ -49,7 +49,6 @@
import static com.android.server.job.controllers.JobStatus.CONSTRAINT_CONTENT_TRIGGER;
import static com.android.server.job.controllers.JobStatus.CONSTRAINT_FLEXIBLE;
import static com.android.server.job.controllers.JobStatus.CONSTRAINT_IDLE;
-import static com.android.server.job.controllers.JobStatus.MIN_WINDOW_FOR_FLEXIBILITY_MS;
import static com.android.server.job.controllers.JobStatus.NO_LATEST_RUNTIME;
import static org.junit.Assert.assertArrayEquals;
@@ -410,10 +409,12 @@
@Test
public void testOnConstantsUpdated_PercentsToDropConstraints() {
+ final long fallbackDuration = 12 * HOUR_IN_MILLIS;
JobInfo.Builder jb = createJob(0)
- .setOverrideDeadline(MIN_WINDOW_FOR_FLEXIBILITY_MS);
+ .setOverrideDeadline(HOUR_IN_MILLIS);
JobStatus js = createJobStatus("testPercentsToDropConstraintsConfig", jb);
- assertEquals(FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 5,
+ // Even though the override deadline is 1 hour, the fallback duration is still used.
+ assertEquals(FROZEN_TIME + fallbackDuration / 10 * 5,
mFlexibilityController.getNextConstraintDropTimeElapsedLocked(js));
setDeviceConfigString(KEY_PERCENTS_TO_DROP_FLEXIBLE_CONSTRAINTS,
"500=1|2|3|4"
@@ -441,13 +442,13 @@
mFlexibilityController.mFcConfig.PERCENTS_TO_DROP_FLEXIBLE_CONSTRAINTS
.get(JobInfo.PRIORITY_MIN),
new int[]{54, 55, 56, 57});
- assertEquals(FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10,
+ assertEquals(FROZEN_TIME + fallbackDuration / 10,
mFlexibilityController.getNextConstraintDropTimeElapsedLocked(js));
js.setNumDroppedFlexibleConstraints(1);
- assertEquals(FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 2,
+ assertEquals(FROZEN_TIME + fallbackDuration / 10 * 2,
mFlexibilityController.getNextConstraintDropTimeElapsedLocked(js));
js.setNumDroppedFlexibleConstraints(2);
- assertEquals(FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 3,
+ assertEquals(FROZEN_TIME + fallbackDuration / 10 * 3,
mFlexibilityController.getNextConstraintDropTimeElapsedLocked(js));
}
@@ -504,37 +505,38 @@
@Test
public void testGetNextConstraintDropTimeElapsedLocked() {
+ final long fallbackDuration = 50 * HOUR_IN_MILLIS;
setDeviceConfigLong(KEY_FALLBACK_FLEXIBILITY_DEADLINE, 200 * HOUR_IN_MILLIS);
setDeviceConfigString(KEY_FALLBACK_FLEXIBILITY_DEADLINES,
"500=" + HOUR_IN_MILLIS
+ ",400=" + 25 * HOUR_IN_MILLIS
- + ",300=" + 50 * HOUR_IN_MILLIS
+ + ",300=" + fallbackDuration
+ ",200=" + 100 * HOUR_IN_MILLIS
+ ",100=" + 200 * HOUR_IN_MILLIS);
long nextTimeToDropNumConstraints;
// no delay, deadline
- JobInfo.Builder jb = createJob(0).setOverrideDeadline(MIN_WINDOW_FOR_FLEXIBILITY_MS);
+ JobInfo.Builder jb = createJob(0).setOverrideDeadline(HOUR_IN_MILLIS);
JobStatus js = createJobStatus("time", jb);
assertEquals(JobStatus.NO_EARLIEST_RUNTIME, js.getEarliestRunTime());
- assertEquals(MIN_WINDOW_FOR_FLEXIBILITY_MS + FROZEN_TIME, js.getLatestRunTimeElapsed());
+ assertEquals(HOUR_IN_MILLIS + FROZEN_TIME, js.getLatestRunTimeElapsed());
assertEquals(FROZEN_TIME, js.enqueueTime);
nextTimeToDropNumConstraints = mFlexibilityController
.getNextConstraintDropTimeElapsedLocked(js);
- assertEquals(FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 5,
+ assertEquals(FROZEN_TIME + fallbackDuration / 10 * 5,
nextTimeToDropNumConstraints);
js.setNumDroppedFlexibleConstraints(1);
nextTimeToDropNumConstraints = mFlexibilityController
.getNextConstraintDropTimeElapsedLocked(js);
- assertEquals(FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 6,
+ assertEquals(FROZEN_TIME + fallbackDuration / 10 * 6,
nextTimeToDropNumConstraints);
js.setNumDroppedFlexibleConstraints(2);
nextTimeToDropNumConstraints = mFlexibilityController
.getNextConstraintDropTimeElapsedLocked(js);
- assertEquals(FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 7,
+ assertEquals(FROZEN_TIME + fallbackDuration / 10 * 7,
nextTimeToDropNumConstraints);
// delay, no deadline
@@ -574,81 +576,83 @@
// delay, deadline
jb = createJob(0)
- .setOverrideDeadline(2 * MIN_WINDOW_FOR_FLEXIBILITY_MS)
- .setMinimumLatency(MIN_WINDOW_FOR_FLEXIBILITY_MS);
+ .setOverrideDeadline(2 * HOUR_IN_MILLIS)
+ .setMinimumLatency(HOUR_IN_MILLIS);
js = createJobStatus("time", jb);
- final long windowStart = FROZEN_TIME + MIN_WINDOW_FOR_FLEXIBILITY_MS;
+ final long windowStart = FROZEN_TIME + HOUR_IN_MILLIS;
nextTimeToDropNumConstraints = mFlexibilityController
.getNextConstraintDropTimeElapsedLocked(js);
- assertEquals(windowStart + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 5,
+ assertEquals(windowStart + fallbackDuration / 10 * 5,
nextTimeToDropNumConstraints);
js.setNumDroppedFlexibleConstraints(1);
nextTimeToDropNumConstraints = mFlexibilityController
.getNextConstraintDropTimeElapsedLocked(js);
- assertEquals(windowStart + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 6,
+ assertEquals(windowStart + fallbackDuration / 10 * 6,
nextTimeToDropNumConstraints);
js.setNumDroppedFlexibleConstraints(2);
nextTimeToDropNumConstraints = mFlexibilityController
.getNextConstraintDropTimeElapsedLocked(js);
- assertEquals(windowStart + MIN_WINDOW_FOR_FLEXIBILITY_MS / 10 * 7,
+ assertEquals(windowStart + fallbackDuration / 10 * 7,
nextTimeToDropNumConstraints);
}
@Test
public void testCurPercent() {
+ final long fallbackDuration = 10 * HOUR_IN_MILLIS;
+ setDeviceConfigString(KEY_FALLBACK_FLEXIBILITY_DEADLINES, "300=" + fallbackDuration);
long deadline = 100 * MINUTE_IN_MILLIS;
long nowElapsed = FROZEN_TIME;
JobInfo.Builder jb = createJob(0).setOverrideDeadline(deadline);
JobStatus js = createJobStatus("time", jb);
assertEquals(FROZEN_TIME, mFlexibilityController.getLifeCycleBeginningElapsedLocked(js));
- assertEquals(deadline + FROZEN_TIME,
+ assertEquals(FROZEN_TIME + fallbackDuration,
mFlexibilityController.getLifeCycleEndElapsedLocked(js, nowElapsed, FROZEN_TIME));
- nowElapsed = FROZEN_TIME + 60 * MINUTE_IN_MILLIS;
+ nowElapsed = FROZEN_TIME + 6 * HOUR_IN_MILLIS;
JobSchedulerService.sElapsedRealtimeClock =
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
assertEquals(60, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
- nowElapsed = FROZEN_TIME + 130 * MINUTE_IN_MILLIS;
+ nowElapsed = FROZEN_TIME + 13 * HOUR_IN_MILLIS;
JobSchedulerService.sElapsedRealtimeClock =
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
assertEquals(100, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
- nowElapsed = FROZEN_TIME + 95 * MINUTE_IN_MILLIS;
+ nowElapsed = FROZEN_TIME + 9 * HOUR_IN_MILLIS;
JobSchedulerService.sElapsedRealtimeClock =
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
- assertEquals(95, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
+ assertEquals(90, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
nowElapsed = FROZEN_TIME;
JobSchedulerService.sElapsedRealtimeClock =
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
- long delay = MINUTE_IN_MILLIS;
- deadline = 101 * MINUTE_IN_MILLIS;
+ long delay = HOUR_IN_MILLIS;
+ deadline = HOUR_IN_MILLIS + 100 * MINUTE_IN_MILLIS;
jb = createJob(0).setOverrideDeadline(deadline).setMinimumLatency(delay);
js = createJobStatus("time", jb);
assertEquals(FROZEN_TIME + delay,
mFlexibilityController.getLifeCycleBeginningElapsedLocked(js));
- assertEquals(deadline + FROZEN_TIME,
+ assertEquals(FROZEN_TIME + delay + fallbackDuration,
mFlexibilityController.getLifeCycleEndElapsedLocked(js, nowElapsed,
FROZEN_TIME + delay));
- nowElapsed = FROZEN_TIME + delay + 60 * MINUTE_IN_MILLIS;
+ nowElapsed = FROZEN_TIME + delay + 6 * HOUR_IN_MILLIS;
JobSchedulerService.sElapsedRealtimeClock =
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
assertEquals(60, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
- nowElapsed = FROZEN_TIME + 130 * MINUTE_IN_MILLIS;
+ nowElapsed = FROZEN_TIME + 13 * HOUR_IN_MILLIS;
JobSchedulerService.sElapsedRealtimeClock =
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
assertEquals(100, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
- nowElapsed = FROZEN_TIME + delay + 95 * MINUTE_IN_MILLIS;
+ nowElapsed = FROZEN_TIME + delay + 9 * HOUR_IN_MILLIS;
JobSchedulerService.sElapsedRealtimeClock =
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
- assertEquals(95, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
+ assertEquals(90, mFlexibilityController.getCurPercentOfLifecycleLocked(js, nowElapsed));
}
@Test
@@ -786,26 +790,27 @@
// deadline
JobInfo.Builder jb = createJob(0).setOverrideDeadline(HOUR_IN_MILLIS);
JobStatus js = createJobStatus("time", jb);
- assertEquals(HOUR_IN_MILLIS + FROZEN_TIME,
- mFlexibilityController.getLifeCycleEndElapsedLocked(js, nowElapsed, 0));
+ assertEquals(3 * HOUR_IN_MILLIS + js.enqueueTime,
+ mFlexibilityController
+ .getLifeCycleEndElapsedLocked(js, nowElapsed, js.enqueueTime));
// no deadline
- assertEquals(FROZEN_TIME + 2 * HOUR_IN_MILLIS,
+ assertEquals(js.enqueueTime + 2 * HOUR_IN_MILLIS,
mFlexibilityController.getLifeCycleEndElapsedLocked(
createJobStatus("time", createJob(0).setPriority(JobInfo.PRIORITY_HIGH)),
- nowElapsed, 100L));
- assertEquals(FROZEN_TIME + 3 * HOUR_IN_MILLIS,
+ nowElapsed, js.enqueueTime));
+ assertEquals(js.enqueueTime + 3 * HOUR_IN_MILLIS,
mFlexibilityController.getLifeCycleEndElapsedLocked(
createJobStatus("time", createJob(0).setPriority(JobInfo.PRIORITY_DEFAULT)),
- nowElapsed, 100L));
- assertEquals(FROZEN_TIME + 4 * HOUR_IN_MILLIS,
+ nowElapsed, js.enqueueTime));
+ assertEquals(js.enqueueTime + 4 * HOUR_IN_MILLIS,
mFlexibilityController.getLifeCycleEndElapsedLocked(
createJobStatus("time", createJob(0).setPriority(JobInfo.PRIORITY_LOW)),
- nowElapsed, 100L));
- assertEquals(FROZEN_TIME + 5 * HOUR_IN_MILLIS,
+ nowElapsed, js.enqueueTime));
+ assertEquals(js.enqueueTime + 5 * HOUR_IN_MILLIS,
mFlexibilityController.getLifeCycleEndElapsedLocked(
createJobStatus("time", createJob(0).setPriority(JobInfo.PRIORITY_MIN)),
- nowElapsed, 100L));
+ nowElapsed, js.enqueueTime));
}
@Test
@@ -871,14 +876,16 @@
mFlexibilityController.prepareForExecutionLocked(jsLow);
mFlexibilityController.prepareForExecutionLocked(jsMin);
- // deadline
- JobInfo.Builder jb = createJob(0).setOverrideDeadline(HOUR_IN_MILLIS);
- JobStatus js = createJobStatus("testGetLifeCycleEndElapsedLocked_ScoreAddition", jb);
- assertEquals(HOUR_IN_MILLIS + FROZEN_TIME,
- mFlexibilityController.getLifeCycleEndElapsedLocked(js, nowElapsed, 0));
+ final long longDeadlineMs = 14 * 24 * HOUR_IN_MILLIS;
+ JobInfo.Builder jbWithLongDeadline = createJob(0).setOverrideDeadline(longDeadlineMs);
+ JobStatus jsWithLongDeadline = createJobStatus(
+ "testGetLifeCycleEndElapsedLocked_ScoreAddition", jbWithLongDeadline);
+ JobInfo.Builder jbWithShortDeadline =
+ createJob(0).setOverrideDeadline(15 * MINUTE_IN_MILLIS);
+ JobStatus jsWithShortDeadline = createJobStatus(
+ "testGetLifeCycleEndElapsedLocked_ScoreAddition", jbWithShortDeadline);
final long earliestMs = 123L;
- // no deadline
assertEquals(earliestMs + HOUR_IN_MILLIS + 5 * 15 * MINUTE_IN_MILLIS,
mFlexibilityController.getLifeCycleEndElapsedLocked(
createJobStatus("testGetLifeCycleEndElapsedLocked_ScoreAddition",
@@ -894,6 +901,9 @@
createJobStatus("testGetLifeCycleEndElapsedLocked_ScoreAddition",
createJob(0).setPriority(JobInfo.PRIORITY_DEFAULT)),
nowElapsed, earliestMs));
+ assertEquals(earliestMs + HOUR_IN_MILLIS + 3 * 15 * MINUTE_IN_MILLIS,
+ mFlexibilityController.getLifeCycleEndElapsedLocked(
+ jsWithShortDeadline, nowElapsed, earliestMs));
assertEquals(earliestMs + HOUR_IN_MILLIS + 2 * 15 * MINUTE_IN_MILLIS,
mFlexibilityController.getLifeCycleEndElapsedLocked(
createJobStatus("testGetLifeCycleEndElapsedLocked_ScoreAddition",
@@ -904,6 +914,9 @@
createJobStatus("testGetLifeCycleEndElapsedLocked_ScoreAddition",
createJob(0).setPriority(JobInfo.PRIORITY_MIN)),
nowElapsed, earliestMs));
+ assertEquals(jsWithLongDeadline.enqueueTime + longDeadlineMs,
+ mFlexibilityController.getLifeCycleEndElapsedLocked(
+ jsWithLongDeadline, nowElapsed, earliestMs));
}
@Test
@@ -1033,8 +1046,8 @@
JobInfo.Builder jb = createJob(0);
jb.setMinimumLatency(1);
jb.setOverrideDeadline(2);
- JobStatus js = createJobStatus("Disable Flexible When Job Has Short Window", jb);
- assertFalse(js.hasFlexibilityConstraint());
+ JobStatus js = createJobStatus("testExceptions_ShortWindow", jb);
+ assertTrue(js.hasFlexibilityConstraint());
}
@Test
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityServiceConnectionTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityServiceConnectionTest.java
index ef80b59..f86cb7b 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityServiceConnectionTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityServiceConnectionTest.java
@@ -21,9 +21,12 @@
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
+import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.notNull;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -31,10 +34,14 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.Manifest;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.AccessibilityTrace;
+import android.accessibilityservice.BrailleDisplayController;
import android.accessibilityservice.GestureDescription;
import android.accessibilityservice.IAccessibilityServiceClient;
+import android.accessibilityservice.IBrailleDisplayConnection;
+import android.accessibilityservice.IBrailleDisplayController;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -43,6 +50,9 @@
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.hardware.display.DisplayManager;
+import android.hardware.usb.UsbDevice;
+import android.hardware.usb.UsbManager;
+import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -62,7 +72,9 @@
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.util.Arrays;
@@ -94,18 +106,30 @@
AccessibilityServiceInfo mServiceInfo;
@Mock ResolveInfo mMockResolveInfo;
@Mock AccessibilitySecurityPolicy mMockSecurityPolicy;
- @Mock AccessibilityWindowManager mMockA11yWindowManager;
- @Mock ActivityTaskManagerInternal mMockActivityTaskManagerInternal;
- @Mock AbstractAccessibilityServiceConnection.SystemSupport mMockSystemSupport;
- @Mock AccessibilityTrace mMockA11yTrace;
- @Mock WindowManagerInternal mMockWindowManagerInternal;
- @Mock SystemActionPerformer mMockSystemActionPerformer;
- @Mock KeyEventDispatcher mMockKeyEventDispatcher;
+ @Mock
+ AccessibilityWindowManager mMockA11yWindowManager;
+ @Mock
+ ActivityTaskManagerInternal mMockActivityTaskManagerInternal;
+ @Mock
+ AbstractAccessibilityServiceConnection.SystemSupport mMockSystemSupport;
+ @Mock
+ AccessibilityTrace mMockA11yTrace;
+ @Mock
+ WindowManagerInternal mMockWindowManagerInternal;
+ @Mock
+ SystemActionPerformer mMockSystemActionPerformer;
+ @Mock
+ KeyEventDispatcher mMockKeyEventDispatcher;
@Mock
MagnificationProcessor mMockMagnificationProcessor;
- @Mock IBinder mMockIBinder;
- @Mock IAccessibilityServiceClient mMockServiceClient;
- @Mock MotionEventInjector mMockMotionEventInjector;
+ @Mock
+ IBinder mMockIBinder;
+ @Mock
+ IAccessibilityServiceClient mMockServiceClient;
+ @Mock
+ IBrailleDisplayController mMockBrailleDisplayController;
+ @Mock
+ MotionEventInjector mMockMotionEventInjector;
MessageCapturingHandler mHandler = new MessageCapturingHandler(null);
@@ -134,6 +158,7 @@
mMockWindowManagerInternal, mMockSystemActionPerformer,
mMockA11yWindowManager, mMockActivityTaskManagerInternal);
when(mMockSecurityPolicy.canPerformGestures(mConnection)).thenReturn(true);
+ when(mMockSecurityPolicy.checkAccessibilityAccess(mConnection)).thenReturn(true);
}
@After
@@ -291,6 +316,119 @@
}
@Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectBluetoothBrailleDisplay() throws Exception {
+ final String macAddress = "00:11:22:33:AA:BB";
+ final byte[] descriptor = {0x05, 0x41};
+ Bundle bd = new Bundle();
+ bd.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_HIDRAW_PATH, "/dev/null");
+ bd.putByteArray(BrailleDisplayController.TEST_BRAILLE_DISPLAY_DESCRIPTOR, descriptor);
+ bd.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_UNIQUE_ID, macAddress);
+ bd.putBoolean(BrailleDisplayController.TEST_BRAILLE_DISPLAY_BUS_BLUETOOTH, true);
+ mConnection.setTestBrailleDisplayData(List.of(bd));
+
+ mConnection.connectBluetoothBrailleDisplay(macAddress, mMockBrailleDisplayController);
+
+ ArgumentCaptor<IBrailleDisplayConnection> connection =
+ ArgumentCaptor.forClass(IBrailleDisplayConnection.class);
+ verify(mMockBrailleDisplayController).onConnected(connection.capture(), eq(descriptor));
+ // Cleanup the connection.
+ connection.getValue().disconnect();
+ }
+
+ @Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectBluetoothBrailleDisplay_throwsForMissingBluetoothConnectPermission() {
+ doThrow(SecurityException.class).when(mMockContext)
+ .enforceCallingPermission(eq(Manifest.permission.BLUETOOTH_CONNECT), any());
+
+ assertThrows(SecurityException.class,
+ () -> mConnection.connectBluetoothBrailleDisplay("unused",
+ mMockBrailleDisplayController));
+ }
+
+ @Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectBluetoothBrailleDisplay_throwsForNullMacAddress() {
+ assertThrows(NullPointerException.class,
+ () -> mConnection.connectBluetoothBrailleDisplay(null,
+ mMockBrailleDisplayController));
+ }
+
+ @Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectBluetoothBrailleDisplay_throwsForMisformattedMacAddress() {
+ assertThrows(IllegalArgumentException.class,
+ () -> mConnection.connectBluetoothBrailleDisplay("12:34",
+ mMockBrailleDisplayController));
+ }
+
+ @Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectUsbBrailleDisplay() throws Exception {
+ final String serialNumber = "myUsbDevice";
+ final byte[] descriptor = {0x05, 0x41};
+ Bundle bd = new Bundle();
+ bd.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_HIDRAW_PATH, "/dev/null");
+ bd.putByteArray(BrailleDisplayController.TEST_BRAILLE_DISPLAY_DESCRIPTOR, descriptor);
+ bd.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_UNIQUE_ID, serialNumber);
+ bd.putBoolean(BrailleDisplayController.TEST_BRAILLE_DISPLAY_BUS_BLUETOOTH, false);
+ mConnection.setTestBrailleDisplayData(List.of(bd));
+ UsbDevice usbDevice = Mockito.mock(UsbDevice.class);
+ when(usbDevice.getSerialNumber()).thenReturn(serialNumber);
+ UsbManager usbManager = Mockito.mock(UsbManager.class);
+ when(mMockContext.getSystemService(Context.USB_SERVICE)).thenReturn(usbManager);
+ when(usbManager.hasPermission(eq(usbDevice), eq(COMPONENT_NAME.getPackageName()),
+ anyInt(), anyInt())).thenReturn(true);
+
+ mConnection.connectUsbBrailleDisplay(usbDevice, mMockBrailleDisplayController);
+
+ ArgumentCaptor<IBrailleDisplayConnection> connection =
+ ArgumentCaptor.forClass(IBrailleDisplayConnection.class);
+ verify(mMockBrailleDisplayController).onConnected(connection.capture(), eq(descriptor));
+ // Cleanup the connection.
+ connection.getValue().disconnect();
+ }
+
+ @Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectUsbBrailleDisplay_throwsForMissingUsbPermission() {
+ UsbManager usbManager = Mockito.mock(UsbManager.class);
+ when(mMockContext.getSystemService(Context.USB_SERVICE)).thenReturn(usbManager);
+ when(usbManager.hasPermission(notNull(), eq(COMPONENT_NAME.getPackageName()),
+ anyInt(), anyInt())).thenReturn(false);
+
+ assertThrows(SecurityException.class,
+ () -> mConnection.connectUsbBrailleDisplay(Mockito.mock(UsbDevice.class),
+ mMockBrailleDisplayController));
+ }
+
+ @Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectUsbBrailleDisplay_throwsForNullDevice() {
+ assertThrows(NullPointerException.class,
+ () -> mConnection.connectUsbBrailleDisplay(null, mMockBrailleDisplayController));
+ }
+
+ @Test
+ @RequiresFlagsEnabled(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
+ public void connectUsbBrailleDisplay_callsOnConnectionFailedForEmptySerialNumber()
+ throws Exception {
+ UsbManager usbManager = Mockito.mock(UsbManager.class);
+ when(mMockContext.getSystemService(Context.USB_SERVICE)).thenReturn(usbManager);
+ when(usbManager.hasPermission(notNull(), eq(COMPONENT_NAME.getPackageName()),
+ anyInt(), anyInt())).thenReturn(true);
+ UsbDevice usbDevice = Mockito.mock(UsbDevice.class);
+ when(usbDevice.getSerialNumber()).thenReturn("");
+
+ mConnection.connectUsbBrailleDisplay(usbDevice, mMockBrailleDisplayController);
+
+ verify(mMockBrailleDisplayController).onConnectionFailed(
+ BrailleDisplayController.BrailleDisplayCallback
+ .FLAG_ERROR_BRAILLE_DISPLAY_NOT_FOUND);
+ }
+
+ @Test
@RequiresFlagsEnabled(Flags.FLAG_RESETTABLE_DYNAMIC_PROPERTIES)
public void binderDied_resetA11yServiceInfo() {
final int flag = AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS;
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/BrailleDisplayConnectionTest.java b/services/tests/servicestests/src/com/android/server/accessibility/BrailleDisplayConnectionTest.java
new file mode 100644
index 0000000..7c278ce
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/accessibility/BrailleDisplayConnectionTest.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.accessibility;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+import android.accessibilityservice.BrailleDisplayController;
+import android.os.Bundle;
+import android.testing.DexmakerShareClassLoaderRule;
+
+import com.google.common.truth.Expect;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.nio.file.Path;
+import java.util.List;
+
+/**
+ * Tests for internal details of {@link BrailleDisplayConnection}.
+ *
+ * <p>Prefer adding new tests in CTS where possible.
+ */
+public class BrailleDisplayConnectionTest {
+ private static final Path NULL_PATH = Path.of("/dev/null");
+
+ private BrailleDisplayConnection mBrailleDisplayConnection;
+ @Mock
+ private BrailleDisplayConnection.NativeInterface mNativeInterface;
+ @Mock
+ private AccessibilityServiceConnection mServiceConnection;
+
+ @Rule
+ public final Expect expect = Expect.create();
+
+ // To mock package-private class
+ @Rule
+ public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
+ new DexmakerShareClassLoaderRule();
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ mBrailleDisplayConnection = new BrailleDisplayConnection(new Object(), mServiceConnection);
+ }
+
+ @Test
+ public void defaultNativeScanner_getReportDescriptor_returnsDescriptor() {
+ int descriptorSize = 4;
+ byte[] descriptor = {0xB, 0xE, 0xE, 0xF};
+ when(mNativeInterface.getHidrawDescSize(anyInt())).thenReturn(descriptorSize);
+ when(mNativeInterface.getHidrawDesc(anyInt(), eq(descriptorSize))).thenReturn(descriptor);
+
+ BrailleDisplayConnection.BrailleDisplayScanner scanner =
+ mBrailleDisplayConnection.getDefaultNativeScanner(mNativeInterface);
+
+ assertThat(scanner.getDeviceReportDescriptor(NULL_PATH)).isEqualTo(descriptor);
+ }
+
+ @Test
+ public void defaultNativeScanner_getReportDescriptor_invalidSize_returnsNull() {
+ when(mNativeInterface.getHidrawDescSize(anyInt())).thenReturn(0);
+
+ BrailleDisplayConnection.BrailleDisplayScanner scanner =
+ mBrailleDisplayConnection.getDefaultNativeScanner(mNativeInterface);
+
+ assertThat(scanner.getDeviceReportDescriptor(NULL_PATH)).isNull();
+ }
+
+ @Test
+ public void defaultNativeScanner_getUniqueId_returnsUniq() {
+ String macAddress = "12:34:56:78";
+ when(mNativeInterface.getHidrawUniq(anyInt())).thenReturn(macAddress);
+
+ BrailleDisplayConnection.BrailleDisplayScanner scanner =
+ mBrailleDisplayConnection.getDefaultNativeScanner(mNativeInterface);
+
+ assertThat(scanner.getUniqueId(NULL_PATH)).isEqualTo(macAddress);
+ }
+
+ @Test
+ public void defaultNativeScanner_getDeviceBusType_busUsb() {
+ when(mNativeInterface.getHidrawBusType(anyInt()))
+ .thenReturn(BrailleDisplayConnection.BUS_USB);
+
+ BrailleDisplayConnection.BrailleDisplayScanner scanner =
+ mBrailleDisplayConnection.getDefaultNativeScanner(mNativeInterface);
+
+ assertThat(scanner.getDeviceBusType(NULL_PATH))
+ .isEqualTo(BrailleDisplayConnection.BUS_USB);
+ }
+
+ @Test
+ public void defaultNativeScanner_getDeviceBusType_busBluetooth() {
+ when(mNativeInterface.getHidrawBusType(anyInt()))
+ .thenReturn(BrailleDisplayConnection.BUS_BLUETOOTH);
+
+ BrailleDisplayConnection.BrailleDisplayScanner scanner =
+ mBrailleDisplayConnection.getDefaultNativeScanner(mNativeInterface);
+
+ assertThat(scanner.getDeviceBusType(NULL_PATH))
+ .isEqualTo(BrailleDisplayConnection.BUS_BLUETOOTH);
+ }
+
+ // BrailleDisplayConnection#setTestData() is used to enable CTS testing with
+ // test Braille display data, but its own implementation should also be tested
+ // so that issues in this helper don't cause confusing failures in CTS.
+ @Test
+ public void setTestData_scannerReturnsTestData() {
+ Bundle bd1 = new Bundle(), bd2 = new Bundle();
+
+ Path path1 = Path.of("/dev/path1"), path2 = Path.of("/dev/path2");
+ bd1.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_HIDRAW_PATH, path1.toString());
+ bd2.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_HIDRAW_PATH, path2.toString());
+ byte[] desc1 = {0xB, 0xE}, desc2 = {0xE, 0xF};
+ bd1.putByteArray(BrailleDisplayController.TEST_BRAILLE_DISPLAY_DESCRIPTOR, desc1);
+ bd2.putByteArray(BrailleDisplayController.TEST_BRAILLE_DISPLAY_DESCRIPTOR, desc2);
+ String uniq1 = "uniq1", uniq2 = "uniq2";
+ bd1.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_UNIQUE_ID, uniq1);
+ bd2.putString(BrailleDisplayController.TEST_BRAILLE_DISPLAY_UNIQUE_ID, uniq2);
+ int bus1 = BrailleDisplayConnection.BUS_USB, bus2 = BrailleDisplayConnection.BUS_BLUETOOTH;
+ bd1.putBoolean(BrailleDisplayController.TEST_BRAILLE_DISPLAY_BUS_BLUETOOTH,
+ bus1 == BrailleDisplayConnection.BUS_BLUETOOTH);
+ bd2.putBoolean(BrailleDisplayController.TEST_BRAILLE_DISPLAY_BUS_BLUETOOTH,
+ bus2 == BrailleDisplayConnection.BUS_BLUETOOTH);
+
+ BrailleDisplayConnection.BrailleDisplayScanner scanner =
+ mBrailleDisplayConnection.setTestData(List.of(bd1, bd2));
+
+ expect.that(scanner.getHidrawNodePaths()).containsExactly(path1, path2);
+ expect.that(scanner.getDeviceReportDescriptor(path1)).isEqualTo(desc1);
+ expect.that(scanner.getDeviceReportDescriptor(path2)).isEqualTo(desc2);
+ expect.that(scanner.getUniqueId(path1)).isEqualTo(uniq1);
+ expect.that(scanner.getUniqueId(path2)).isEqualTo(uniq2);
+ expect.that(scanner.getDeviceBusType(path1)).isEqualTo(bus1);
+ expect.that(scanner.getDeviceBusType(path2)).isEqualTo(bus2);
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java b/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
index 26934d8..4307ec5 100644
--- a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
@@ -682,19 +682,19 @@
/* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false);
setUpAndStartUserInBackground(TEST_USER_ID);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID, /* allowDelayedLocking= */ true,
/* keyEvictedCallback= */ null, /* expectLocking= */ true);
setUpAndStartUserInBackground(TEST_USER_ID1);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* allowDelayedLocking= */ true,
/* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true);
setUpAndStartUserInBackground(TEST_USER_ID2);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* delayedLocking= */ false,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* allowDelayedLocking= */ false,
/* keyEvictedCallback= */ null, /* expectLocking= */ true);
setUpAndStartUserInBackground(TEST_USER_ID3);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID3, /* delayedLocking= */ false,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID3, /* allowDelayedLocking= */ false,
/* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true);
}
@@ -739,21 +739,21 @@
mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true,
/* maxRunningUsers= */ 3, /* delayUserDataLocking= */ true);
- // delayedLocking set and no KeyEvictedCallback, so it should not lock.
+ // allowDelayedLocking set and no KeyEvictedCallback, so it should not lock.
setUpAndStartUserInBackground(TEST_USER_ID);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID, /* allowDelayedLocking= */ true,
/* keyEvictedCallback= */ null, /* expectLocking= */ false);
setUpAndStartUserInBackground(TEST_USER_ID1);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* allowDelayedLocking= */ true,
/* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true);
setUpAndStartUserInBackground(TEST_USER_ID2);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* delayedLocking= */ false,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* allowDelayedLocking= */ false,
/* keyEvictedCallback= */ null, /* expectLocking= */ true);
setUpAndStartUserInBackground(TEST_USER_ID3);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID3, /* delayedLocking= */ false,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID3, /* allowDelayedLocking= */ false,
/* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true);
}
@@ -843,7 +843,7 @@
mSetFlagsRule.enableFlags(android.os.Flags.FLAG_ALLOW_PRIVATE_PROFILE,
android.multiuser.Flags.FLAG_ENABLE_BIOMETRICS_TO_UNLOCK_PRIVATE_SPACE);
setUpAndStartProfileInBackground(TEST_USER_ID1, UserManager.USER_TYPE_PROFILE_PRIVATE);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* allowDelayedLocking= */ true,
/* keyEvictedCallback */ null, /* expectLocking= */ false);
}
@@ -855,19 +855,20 @@
mSetFlagsRule.disableFlags(
android.multiuser.Flags.FLAG_ENABLE_BIOMETRICS_TO_UNLOCK_PRIVATE_SPACE);
setUpAndStartProfileInBackground(TEST_USER_ID1, UserManager.USER_TYPE_PROFILE_PRIVATE);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* allowDelayedLocking= */ true,
/* keyEvictedCallback */ null, /* expectLocking= */ true);
mSetFlagsRule.disableFlags(android.os.Flags.FLAG_ALLOW_PRIVATE_PROFILE);
mSetFlagsRule.enableFlags(
android.multiuser.Flags.FLAG_ENABLE_BIOMETRICS_TO_UNLOCK_PRIVATE_SPACE);
setUpAndStartProfileInBackground(TEST_USER_ID2, UserManager.USER_TYPE_PROFILE_PRIVATE);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* allowDelayedLocking= */ true,
/* keyEvictedCallback */ null, /* expectLocking= */ true);
}
+ /** Delayed-locking users (as opposed to devices) have no limits on how many can be unlocked. */
@Test
- public void testStopPrivateProfileWithDelayedLocking_maxRunningUsersBreached()
+ public void testStopPrivateProfileWithDelayedLocking_imperviousToNumberOfRunningUsers()
throws Exception {
mUserController.setInitialConfig(/* mUserSwitchUiEnabled */ true,
/* maxRunningUsers= */ 1, /* delayUserDataLocking= */ false);
@@ -875,10 +876,14 @@
android.multiuser.Flags.FLAG_ENABLE_BIOMETRICS_TO_UNLOCK_PRIVATE_SPACE);
setUpAndStartProfileInBackground(TEST_USER_ID1, UserManager.USER_TYPE_PROFILE_PRIVATE);
setUpAndStartProfileInBackground(TEST_USER_ID2, UserManager.USER_TYPE_PROFILE_MANAGED);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true,
- /* keyEvictedCallback */ null, /* expectLocking= */ true);
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* allowDelayedLocking= */ true,
+ /* keyEvictedCallback */ null, /* expectLocking= */ false);
}
+ /**
+ * Tests that when a device/user (managed profile) does not permit delayed locking, then
+ * even if allowDelayedLocking is true, the user will still be locked.
+ */
@Test
public void testStopManagedProfileWithDelayedLocking() throws Exception {
mUserController.setInitialConfig(/* mUserSwitchUiEnabled */ true,
@@ -886,7 +891,7 @@
mSetFlagsRule.enableFlags(android.os.Flags.FLAG_ALLOW_PRIVATE_PROFILE,
android.multiuser.Flags.FLAG_ENABLE_BIOMETRICS_TO_UNLOCK_PRIVATE_SPACE);
setUpAndStartProfileInBackground(TEST_USER_ID1, UserManager.USER_TYPE_PROFILE_MANAGED);
- assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true,
+ assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* allowDelayedLocking= */ true,
/* keyEvictedCallback */ null, /* expectLocking= */ true);
}
@@ -1087,29 +1092,29 @@
mUserStates.put(userId, mUserController.getStartedUserState(userId));
}
- private void assertUserLockedOrUnlockedAfterStopping(int userId, boolean delayedLocking,
+ private void assertUserLockedOrUnlockedAfterStopping(int userId, boolean allowDelayedLocking,
KeyEvictedCallback keyEvictedCallback, boolean expectLocking) throws Exception {
- int r = mUserController.stopUser(userId, /* force= */ true, /* delayedLocking= */
- delayedLocking, null, keyEvictedCallback);
+ int r = mUserController.stopUser(userId, /* force= */ true, /* allowDelayedLocking= */
+ allowDelayedLocking, null, keyEvictedCallback);
assertThat(r).isEqualTo(ActivityManager.USER_OP_SUCCESS);
- assertUserLockedOrUnlockedState(userId, delayedLocking, expectLocking);
+ assertUserLockedOrUnlockedState(userId, allowDelayedLocking, expectLocking);
}
private void assertProfileLockedOrUnlockedAfterStopping(int userId, boolean expectLocking)
throws Exception {
boolean profileStopped = mUserController.stopProfile(userId);
assertThat(profileStopped).isTrue();
- assertUserLockedOrUnlockedState(userId, /* delayedLocking= */ false, expectLocking);
+ assertUserLockedOrUnlockedState(userId, /* allowDelayedLocking= */ false, expectLocking);
}
- private void assertUserLockedOrUnlockedState(int userId, boolean delayedLocking,
+ private void assertUserLockedOrUnlockedState(int userId, boolean allowDelayedLocking,
boolean expectLocking) throws InterruptedException, RemoteException {
// fake all interim steps
UserState ussUser = mUserStates.get(userId);
ussUser.setState(UserState.STATE_SHUTDOWN);
// Passing delayedLocking invalidates incorrect internal data passing but currently there is
// no easy way to get that information passed through lambda.
- mUserController.finishUserStopped(ussUser, delayedLocking);
+ mUserController.finishUserStopped(ussUser, allowDelayedLocking);
waitForHandlerToComplete(FgThread.getHandler(), HANDLER_WAIT_TIME_MS);
verify(mInjector.mStorageManagerMock, times(expectLocking ? 1 : 0))
.lockCeStorage(userId);
diff --git a/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java
index fa39364..b705077 100644
--- a/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java
@@ -31,6 +31,7 @@
import static org.testng.Assert.assertThrows;
import android.annotation.NonNull;
+import android.hardware.devicestate.DeviceState;
import android.hardware.devicestate.DeviceStateInfo;
import android.hardware.devicestate.DeviceStateRequest;
import android.hardware.devicestate.IDeviceStateManagerCallback;
@@ -72,7 +73,8 @@
new DeviceState(0, "DEFAULT", 0 /* flags */);
private static final DeviceState OTHER_DEVICE_STATE =
new DeviceState(1, "OTHER", 0 /* flags */);
- private static final DeviceState DEVICE_STATE_CANCEL_WHEN_REQUESTER_NOT_ON_TOP =
+ private static final DeviceState
+ DEVICE_STATE_CANCEL_WHEN_REQUESTER_NOT_ON_TOP =
new DeviceState(2, "DEVICE_STATE_CANCEL_WHEN_REQUESTER_NOT_ON_TOP",
DeviceState.FLAG_CANCEL_WHEN_REQUESTER_NOT_ON_TOP /* flags */);
// A device state that is not reported as being supported for the default test provider.
diff --git a/services/tests/servicestests/src/com/android/server/devicestate/OverrideRequestControllerTest.java b/services/tests/servicestests/src/com/android/server/devicestate/OverrideRequestControllerTest.java
index b3d25f2..cfdb586 100644
--- a/services/tests/servicestests/src/com/android/server/devicestate/OverrideRequestControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicestate/OverrideRequestControllerTest.java
@@ -25,6 +25,7 @@
import static junit.framework.Assert.assertNull;
import android.annotation.Nullable;
+import android.hardware.devicestate.DeviceState;
import android.hardware.devicestate.DeviceStateRequest;
import android.os.Binder;
import android.platform.test.annotations.Presubmit;
@@ -48,8 +49,10 @@
@RunWith(AndroidJUnit4.class)
public final class OverrideRequestControllerTest {
- private static final DeviceState TEST_DEVICE_STATE_ZERO = new DeviceState(0, "TEST_STATE", 0);
- private static final DeviceState TEST_DEVICE_STATE_ONE = new DeviceState(1, "TEST_STATE", 0);
+ private static final DeviceState
+ TEST_DEVICE_STATE_ZERO = new DeviceState(0, "TEST_STATE", 0);
+ private static final DeviceState
+ TEST_DEVICE_STATE_ONE = new DeviceState(1, "TEST_STATE", 0);
private TestStatusChangeListener mStatusListener;
private OverrideRequestController mController;
diff --git a/services/tests/servicestests/src/com/android/server/policy/DeviceStateProviderImplTest.java b/services/tests/servicestests/src/com/android/server/policy/DeviceStateProviderImplTest.java
index 7e40f96..16909ab 100644
--- a/services/tests/servicestests/src/com/android/server/policy/DeviceStateProviderImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/policy/DeviceStateProviderImplTest.java
@@ -40,12 +40,12 @@
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
+import android.hardware.devicestate.DeviceState;
import android.os.PowerManager;
import androidx.annotation.NonNull;
import com.android.server.LocalServices;
-import com.android.server.devicestate.DeviceState;
import com.android.server.devicestate.DeviceStateProvider;
import com.android.server.input.InputManagerInternal;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
index 344a4b0..4dded1d 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
@@ -16,6 +16,7 @@
package com.android.server.notification;
import static android.content.Context.DEVICE_POLICY_SERVICE;
+import static android.app.Flags.FLAG_LIFETIME_EXTENSION_REFACTOR;
import static android.os.UserManager.USER_TYPE_FULL_SECONDARY;
import static android.os.UserManager.USER_TYPE_PROFILE_CLONE;
import static android.os.UserManager.USER_TYPE_PROFILE_MANAGED;
@@ -62,6 +63,7 @@
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
+import android.platform.test.annotations.EnableFlags;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.ArrayMap;
@@ -1983,6 +1985,22 @@
new ComponentName("pkg1", "cmp1"))).isFalse();
}
+ @Test
+ @EnableFlags(FLAG_LIFETIME_EXTENSION_REFACTOR)
+ public void testManagedServiceInfoIsSystemUi() {
+ ManagedServices service = new TestManagedServices(getContext(), mLock, mUserProfiles, mIpm,
+ APPROVAL_BY_COMPONENT);
+
+ ManagedServices.ManagedServiceInfo service0 = service.new ManagedServiceInfo(
+ mock(IInterface.class), ComponentName.unflattenFromString("a/a"), 0, false,
+ mock(ServiceConnection.class), 26, 34);
+
+ service0.isSystemUi = true;
+ assertThat(service0.isSystemUi()).isTrue();
+ service0.isSystemUi = false;
+ assertThat(service0.isSystemUi()).isFalse();
+ }
+
private void mockServiceInfoWithMetaData(List<ComponentName> componentNames,
ManagedServices service, ArrayMap<ComponentName, Bundle> metaDatas)
throws RemoteException {
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 96ffec1..046e057 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -2545,6 +2545,17 @@
assertThat(mBinderService.getActiveNotifications(sbn.getPackageName()).length).isEqualTo(1);
assertThat(mService.getNotificationRecordCount()).isEqualTo(1);
+ // Checks that a post update is sent.
+ verify(mWorkerHandler, times(1))
+ .post(any(NotificationManagerService.PostNotificationRunnable.class));
+ ArgumentCaptor<NotificationRecord> captor =
+ ArgumentCaptor.forClass(NotificationRecord.class);
+ verify(mListeners, times(1)).prepareNotifyPostedLocked(captor.capture(), any(),
+ anyBoolean());
+ assertThat(captor.getValue().getNotification().flags
+ & FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY).isEqualTo(
+ FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY);
+
mSetFlagsRule.disableFlags(android.app.Flags.FLAG_LIFETIME_EXTENSION_REFACTOR);
mBinderService.cancelNotificationWithTag(PKG, PKG, sbn.getTag(), sbn.getId(),
sbn.getUserId());
@@ -2577,6 +2588,17 @@
StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
assertThat(notifs.length).isEqualTo(1);
assertThat(notifs[0].getId()).isEqualTo(1);
+
+ // Checks that a post update is sent.
+ verify(mWorkerHandler, times(1))
+ .post(any(NotificationManagerService.PostNotificationRunnable.class));
+ ArgumentCaptor<NotificationRecord> captor =
+ ArgumentCaptor.forClass(NotificationRecord.class);
+ verify(mListeners, times(1)).prepareNotifyPostedLocked(captor.capture(), any(),
+ anyBoolean());
+ assertThat(captor.getValue().getNotification().flags
+ & FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY).isEqualTo(
+ FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY);
}
@Test
@@ -2985,18 +3007,29 @@
public void testCancelNotificationsFromListener_clearAll_NoClearLifetimeExt()
throws Exception {
mSetFlagsRule.enableFlags(android.app.Flags.FLAG_LIFETIME_EXTENSION_REFACTOR);
-
final NotificationRecord notif = generateNotificationRecord(
mTestNotificationChannel, 1, null, false);
- notif.getNotification().flags = FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY;
+ notif.getNotification().flags |= FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY;
mService.addNotification(notif);
-
+ verify(mWorkerHandler, times(0))
+ .post(any(NotificationManagerService.PostNotificationRunnable.class));
mService.getBinderService().cancelNotificationsFromListener(null, null);
waitForIdle();
-
+ // Notification not cancelled.
StatusBarNotification[] notifs =
mBinderService.getActiveNotifications(notif.getSbn().getPackageName());
assertThat(notifs.length).isEqualTo(1);
+
+ // Checks that a post update is sent.
+ verify(mWorkerHandler, times(1))
+ .post(any(NotificationManagerService.PostNotificationRunnable.class));
+ ArgumentCaptor<NotificationRecord> captor =
+ ArgumentCaptor.forClass(NotificationRecord.class);
+ verify(mListeners, times(1)).prepareNotifyPostedLocked(captor.capture(), any(),
+ anyBoolean());
+ assertThat(captor.getValue().getNotification().flags
+ & FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY).isEqualTo(
+ FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY);
}
@Test
@@ -3217,6 +3250,17 @@
StatusBarNotification[] notifs =
mBinderService.getActiveNotifications(notif.getSbn().getPackageName());
assertEquals(1, notifs.length);
+
+ // Checks that a post update is sent.
+ verify(mWorkerHandler, times(1))
+ .post(any(NotificationManagerService.PostNotificationRunnable.class));
+ ArgumentCaptor<NotificationRecord> captor =
+ ArgumentCaptor.forClass(NotificationRecord.class);
+ verify(mListeners, times(1)).prepareNotifyPostedLocked(captor.capture(), any(),
+ anyBoolean());
+ assertThat(captor.getValue().getNotification().flags
+ & FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY).isEqualTo(
+ FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY);
}
@Test
@@ -5659,6 +5703,17 @@
StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
assertThat(notifsAfter.length).isEqualTo(1);
assertThat(mService.getNotificationRecord(notif.getKey())).isEqualTo(notif);
+
+ // Checks that a post update is sent.
+ verify(mWorkerHandler, times(1))
+ .post(any(NotificationManagerService.PostNotificationRunnable.class));
+ ArgumentCaptor<NotificationRecord> captor =
+ ArgumentCaptor.forClass(NotificationRecord.class);
+ verify(mListeners, times(1)).prepareNotifyPostedLocked(captor.capture(), any(),
+ anyBoolean());
+ assertThat(captor.getValue().getNotification().flags
+ & FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY).isEqualTo(
+ FLAG_LIFETIME_EXTENDED_BY_DIRECT_REPLY);
}
@Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
index 1fb7cd8..9e2b1ec 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
@@ -32,14 +32,17 @@
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
+import static com.android.server.wm.DragDropController.MSG_UNHANDLED_DROP_LISTENER_TIMEOUT;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.app.PendingIntent;
@@ -49,9 +52,12 @@
import android.content.pm.ShortcutServiceInternal;
import android.graphics.PixelFormat;
import android.os.Binder;
+import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
+import android.os.Message;
import android.os.Parcelable;
+import android.os.RemoteException;
import android.os.UserHandle;
import android.platform.test.annotations.Presubmit;
import android.view.DragEvent;
@@ -61,6 +67,7 @@
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
+import android.window.IUnhandledDragListener;
import androidx.test.filters.SmallTest;
@@ -533,14 +540,98 @@
});
}
+ @Test
+ public void testUnhandledDragListenerNotCalledForNormalDrags() throws RemoteException {
+ assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
+
+ final IUnhandledDragListener listener = mock(IUnhandledDragListener.class);
+ doReturn(mock(Binder.class)).when(listener).asBinder();
+ mTarget.setUnhandledDragListener(listener);
+ doDragAndDrop(0, ClipData.newPlainText("label", "Test"), 0, 0);
+ verify(listener, times(0)).onUnhandledDrop(any(), any());
+ }
+
+ @Test
+ public void testUnhandledDragListenerReceivesUnhandledDropOverWindow() {
+ assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
+
+ final IUnhandledDragListener listener = mock(IUnhandledDragListener.class);
+ doReturn(mock(Binder.class)).when(listener).asBinder();
+ mTarget.setUnhandledDragListener(listener);
+ final int invalidXY = 100_000;
+ startDrag(View.DRAG_FLAG_GLOBAL, ClipData.newPlainText("label", "Test"), () -> {
+ // Notify the unhandled drag listener
+ mTarget.reportDropWindow(mWindow.mInputChannelToken, invalidXY, invalidXY);
+ mTarget.handleMotionEvent(false /* keepHandling */, invalidXY, invalidXY);
+ mTarget.reportDropResult(mWindow.mClient, false);
+ mTarget.onUnhandledDropCallback(true);
+ mToken = null;
+ try {
+ verify(listener, times(1)).onUnhandledDrop(any(), any());
+ } catch (RemoteException e) {
+ fail("Failed to verify unhandled drop: " + e);
+ }
+ });
+ }
+
+ @Test
+ public void testUnhandledDragListenerReceivesUnhandledDropOverNoValidWindow() {
+ assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
+
+ final IUnhandledDragListener listener = mock(IUnhandledDragListener.class);
+ doReturn(mock(Binder.class)).when(listener).asBinder();
+ mTarget.setUnhandledDragListener(listener);
+ final int invalidXY = 100_000;
+ startDrag(View.DRAG_FLAG_GLOBAL, ClipData.newPlainText("label", "Test"), () -> {
+ // Notify the unhandled drag listener
+ mTarget.reportDropWindow(mock(IBinder.class), invalidXY, invalidXY);
+ mTarget.handleMotionEvent(false /* keepHandling */, invalidXY, invalidXY);
+ mTarget.onUnhandledDropCallback(true);
+ mToken = null;
+ try {
+ verify(listener, times(1)).onUnhandledDrop(any(), any());
+ } catch (RemoteException e) {
+ fail("Failed to verify unhandled drop: " + e);
+ }
+ });
+ }
+
+ @Test
+ public void testUnhandledDragListenerCallbackTimeout() {
+ assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
+
+ final IUnhandledDragListener listener = mock(IUnhandledDragListener.class);
+ doReturn(mock(Binder.class)).when(listener).asBinder();
+ mTarget.setUnhandledDragListener(listener);
+ final int invalidXY = 100_000;
+ startDrag(View.DRAG_FLAG_GLOBAL, ClipData.newPlainText("label", "Test"), () -> {
+ // Notify the unhandled drag listener
+ mTarget.reportDropWindow(mock(IBinder.class), invalidXY, invalidXY);
+ mTarget.handleMotionEvent(false /* keepHandling */, invalidXY, invalidXY);
+
+ // Verify that the unhandled drop listener callback timeout has been scheduled
+ final Handler handler = mTarget.getHandler();
+ assertTrue(handler.hasMessages(MSG_UNHANDLED_DROP_LISTENER_TIMEOUT));
+
+ // Force trigger the timeout and verify that it actually cleans up the drag & timeout
+ handler.handleMessage(Message.obtain(handler, MSG_UNHANDLED_DROP_LISTENER_TIMEOUT));
+ assertFalse(handler.hasMessages(MSG_UNHANDLED_DROP_LISTENER_TIMEOUT));
+ assertFalse(mTarget.dragDropActiveLocked());
+ mToken = null;
+ });
+ }
+
private void doDragAndDrop(int flags, ClipData data, float dropX, float dropY) {
startDrag(flags, data, () -> {
mTarget.reportDropWindow(mWindow.mInputChannelToken, dropX, dropY);
- mTarget.handleMotionEvent(false, dropX, dropY);
+ mTarget.handleMotionEvent(false /* keepHandling */, dropX, dropY);
mToken = mWindow.mClient.asBinder();
});
}
+ /**
+ * Starts a drag with the given parameters, calls Runnable `r` after drag is started.
+ */
private void startDrag(int flag, ClipData data, Runnable r) {
final SurfaceSession appSession = new SurfaceSession();
try {
diff --git a/services/usb/Android.bp b/services/usb/Android.bp
index 3a0a6ab..e8ffe54 100644
--- a/services/usb/Android.bp
+++ b/services/usb/Android.bp
@@ -34,8 +34,20 @@
"android.hardware.usb-V1.2-java",
"android.hardware.usb-V1.3-java",
"android.hardware.usb-V3-java",
+ "usb_flags_lib",
],
lint: {
baseline_filename: "lint-baseline.xml",
},
}
+
+aconfig_declarations {
+ name: "usb_flags",
+ package: "com.android.server.usb.flags",
+ srcs: ["**/usb_flags.aconfig"],
+}
+
+java_aconfig_library {
+ name: "usb_flags_lib",
+ aconfig_declarations: "usb_flags",
+}
diff --git a/services/usb/java/com/android/server/usb/UsbHandlerManager.java b/services/usb/java/com/android/server/usb/UsbHandlerManager.java
index f311274..d83ff1f 100644
--- a/services/usb/java/com/android/server/usb/UsbHandlerManager.java
+++ b/services/usb/java/com/android/server/usb/UsbHandlerManager.java
@@ -37,7 +37,7 @@
*
* @hide
*/
-class UsbHandlerManager {
+public class UsbHandlerManager {
private static final String LOG_TAG = UsbHandlerManager.class.getSimpleName();
private final Context mContext;
diff --git a/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java b/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java
index f916660..2ff21ad 100644
--- a/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java
+++ b/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java
@@ -18,6 +18,7 @@
import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
+import android.Manifest;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.ActivityManager;
@@ -62,6 +63,7 @@
import com.android.internal.util.dump.DualDumpOutputStream;
import com.android.modules.utils.TypedXmlPullParser;
import com.android.modules.utils.TypedXmlSerializer;
+import com.android.server.usb.flags.Flags;
import com.android.server.utils.EventLogger;
import libcore.io.IoUtils;
@@ -80,8 +82,20 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
-class UsbProfileGroupSettingsManager {
+public class UsbProfileGroupSettingsManager {
+ /**
+ * <application> level property that an app can specify to restrict any overlaying of
+ * activities when usb device is attached.
+ *
+ *
+ * <p>This should only be set by privileged apps having {@link Manifest.permission#MANAGE_USB}
+ * permission.
+ * @hide
+ */
+ public static final String PROPERTY_RESTRICT_USB_OVERLAY_ACTIVITIES =
+ "android.app.PROPERTY_RESTRICT_USB_OVERLAY_ACTIVITIES";
private static final String TAG = UsbProfileGroupSettingsManager.class.getSimpleName();
private static final boolean DEBUG = false;
@@ -101,6 +115,8 @@
private final PackageManager mPackageManager;
+ private final ActivityManager mActivityManager;
+
private final UserManager mUserManager;
private final @NonNull UsbSettingsManager mSettingsManager;
@@ -224,7 +240,7 @@
* @param settingsManager The settings manager of the service
* @param usbResolveActivityManager The resovle activity manager of the service
*/
- UsbProfileGroupSettingsManager(@NonNull Context context, @NonNull UserHandle user,
+ public UsbProfileGroupSettingsManager(@NonNull Context context, @NonNull UserHandle user,
@NonNull UsbSettingsManager settingsManager,
@NonNull UsbHandlerManager usbResolveActivityManager) {
if (DEBUG) Slog.v(TAG, "Creating settings for " + user);
@@ -238,6 +254,7 @@
mContext = context;
mPackageManager = context.getPackageManager();
+ mActivityManager = context.getSystemService(ActivityManager.class);
mSettingsManager = settingsManager;
mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
@@ -895,7 +912,10 @@
// Send broadcast to running activities with registered intent
mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
- resolveActivity(intent, device, true /* showMtpNotification */);
+ //resolving activities only if there is no foreground activity restricting it.
+ if (!shouldRestrictOverlayActivities()) {
+ resolveActivity(intent, device, true /* showMtpNotification */);
+ }
}
private void resolveActivity(Intent intent, UsbDevice device, boolean showMtpNotification) {
@@ -918,6 +938,63 @@
resolveActivity(intent, matches, defaultActivity, device, null);
}
+ /**
+ * @return true if any application in foreground have set restrict_usb_overlay_activities as
+ * true in manifest file. The application needs to have MANAGE_USB permission.
+ */
+ private boolean shouldRestrictOverlayActivities() {
+
+ if (!Flags.allowRestrictionOfOverlayActivities()) return false;
+
+ List<ActivityManager.RunningAppProcessInfo> appProcessInfos = mActivityManager
+ .getRunningAppProcesses();
+
+ List<String> filteredAppProcessInfos = new ArrayList<>();
+ boolean shouldRestrictOverlayActivities;
+
+ //filtering out applications in foreground.
+ for (ActivityManager.RunningAppProcessInfo processInfo : appProcessInfos) {
+ if (processInfo.importance <= ActivityManager
+ .RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
+ filteredAppProcessInfos.addAll(List.of(processInfo.pkgList));
+ }
+ }
+
+ if (DEBUG) Slog.d(TAG, "packages in foreground : " + filteredAppProcessInfos);
+
+ List<String> packagesHoldingManageUsbPermission =
+ mPackageManager.getPackagesHoldingPermissions(
+ new String[]{android.Manifest.permission.MANAGE_USB},
+ PackageManager.MATCH_SYSTEM_ONLY).stream()
+ .map(packageInfo -> packageInfo.packageName).collect(Collectors.toList());
+
+ //retaining only packages that hold the required permission
+ filteredAppProcessInfos.retainAll(packagesHoldingManageUsbPermission);
+
+ if (DEBUG) {
+ Slog.d(TAG, "packages in foreground with required permission : "
+ + filteredAppProcessInfos);
+ }
+
+ shouldRestrictOverlayActivities = filteredAppProcessInfos.stream().anyMatch(pkg -> {
+ try {
+ return mPackageManager.getProperty(PROPERTY_RESTRICT_USB_OVERLAY_ACTIVITIES, pkg)
+ .getBoolean();
+ } catch (NameNotFoundException e) {
+ if (DEBUG) {
+ Slog.d(TAG, "property PROPERTY_RESTRICT_USB_OVERLAY_ACTIVITIES "
+ + "not present for " + pkg);
+ }
+ return false;
+ }
+ });
+
+ if (shouldRestrictOverlayActivities) {
+ Slog.d(TAG, "restricting starting of usb overlay activities");
+ }
+ return shouldRestrictOverlayActivities;
+ }
+
public void deviceAttachedForFixedHandler(UsbDevice device, ComponentName component) {
final Intent intent = createDeviceAttachedIntent(device);
diff --git a/services/usb/java/com/android/server/usb/UsbSettingsManager.java b/services/usb/java/com/android/server/usb/UsbSettingsManager.java
index 8e53ff4..0b854a8 100644
--- a/services/usb/java/com/android/server/usb/UsbSettingsManager.java
+++ b/services/usb/java/com/android/server/usb/UsbSettingsManager.java
@@ -33,7 +33,7 @@
/**
* Maintains all {@link UsbUserSettingsManager} for all users.
*/
-class UsbSettingsManager {
+public class UsbSettingsManager {
private static final String LOG_TAG = UsbSettingsManager.class.getSimpleName();
private static final boolean DEBUG = false;
@@ -70,7 +70,7 @@
*
* @return The settings for the user
*/
- @NonNull UsbUserSettingsManager getSettingsForUser(@UserIdInt int userId) {
+ public @NonNull UsbUserSettingsManager getSettingsForUser(@UserIdInt int userId) {
synchronized (mSettingsByUser) {
UsbUserSettingsManager settings = mSettingsByUser.get(userId);
if (settings == null) {
diff --git a/services/usb/java/com/android/server/usb/UsbUserSettingsManager.java b/services/usb/java/com/android/server/usb/UsbUserSettingsManager.java
index c2b8d01..be729c5 100644
--- a/services/usb/java/com/android/server/usb/UsbUserSettingsManager.java
+++ b/services/usb/java/com/android/server/usb/UsbUserSettingsManager.java
@@ -49,7 +49,7 @@
import java.util.ArrayList;
import java.util.List;
-class UsbUserSettingsManager {
+public class UsbUserSettingsManager {
private static final String TAG = UsbUserSettingsManager.class.getSimpleName();
private static final boolean DEBUG = false;
@@ -81,7 +81,7 @@
*
* @return The resolve infos of the activities that can handle the intent
*/
- List<ResolveInfo> queryIntentActivities(@NonNull Intent intent) {
+ public List<ResolveInfo> queryIntentActivities(@NonNull Intent intent) {
return mPackageManager.queryIntentActivitiesAsUser(intent, PackageManager.GET_META_DATA,
mUser.getIdentifier());
}
diff --git a/services/usb/java/com/android/server/usb/flags/usb_flags.aconfig b/services/usb/java/com/android/server/usb/flags/usb_flags.aconfig
new file mode 100644
index 0000000..ea6e502
--- /dev/null
+++ b/services/usb/java/com/android/server/usb/flags/usb_flags.aconfig
@@ -0,0 +1,8 @@
+package: "com.android.server.usb.flags"
+
+flag {
+ name: "allow_restriction_of_overlay_activities"
+ namespace: "usb"
+ description: "This flag controls the restriction of usb overlay activities"
+ bug: "307231174"
+}
diff --git a/telephony/java/android/telephony/DomainSelectionService.java b/telephony/java/android/telephony/DomainSelectionService.java
index 3c11da5..4ff9712 100644
--- a/telephony/java/android/telephony/DomainSelectionService.java
+++ b/telephony/java/android/telephony/DomainSelectionService.java
@@ -831,7 +831,7 @@
@NonNull String tag, @NonNull String errorLogName) {
try {
CompletableFuture.runAsync(
- () -> TelephonyUtils.runWithCleanCallingIdentity(r), executor).join();
+ () -> TelephonyUtils.runWithCleanCallingIdentity(r), executor);
} catch (CancellationException | CompletionException e) {
Rlog.w(tag, "Binder - " + errorLogName + " exception: " + e.getMessage());
}
diff --git a/tests/UsbManagerTests/Android.bp b/tests/UsbManagerTests/Android.bp
index c02d8e9..70c7dad 100644
--- a/tests/UsbManagerTests/Android.bp
+++ b/tests/UsbManagerTests/Android.bp
@@ -29,12 +29,17 @@
static_libs: [
"frameworks-base-testutils",
"androidx.test.rules",
- "mockito-target-inline-minus-junit4",
+ "mockito-target-extended-minus-junit4",
"platform-test-annotations",
"truth",
"UsbManagerTestLib",
],
- jni_libs: ["libdexmakerjvmtiagent"],
+ jni_libs: [
+ // Required for ExtendedMockito
+ "libdexmakerjvmtiagent",
+ "libmultiplejvmtiagentsinterferenceagent",
+ "libstaticjvmtiagent",
+ ],
certificate: "platform",
platform_apis: true,
test_suites: ["device-tests"],
diff --git a/tests/UsbManagerTests/src/com/android/server/usbtest/UsbProfileGroupSettingsManagerTest.java b/tests/UsbManagerTests/src/com/android/server/usbtest/UsbProfileGroupSettingsManagerTest.java
new file mode 100644
index 0000000..4780d8a
--- /dev/null
+++ b/tests/UsbManagerTests/src/com/android/server/usbtest/UsbProfileGroupSettingsManagerTest.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.usbtest;
+
+import static com.android.server.usb.UsbProfileGroupSettingsManager.PROPERTY_RESTRICT_USB_OVERLAY_ACTIVITIES;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.ActivityManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.Property;
+import android.content.pm.UserInfo;
+import android.content.res.Resources;
+import android.hardware.usb.UsbDevice;
+import android.os.UserHandle;
+import android.os.UserManager;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.dx.mockito.inline.extended.ExtendedMockito;
+import com.android.server.usb.UsbHandlerManager;
+import com.android.server.usb.UsbProfileGroupSettingsManager;
+import com.android.server.usb.UsbSettingsManager;
+import com.android.server.usb.UsbUserSettingsManager;
+import com.android.server.usb.flags.Flags;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoSession;
+import org.mockito.quality.Strictness;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Unit tests for {@link com.android.server.usb.UsbProfileGroupSettingsManager}.
+ * Note: MUST claim MANAGE_USB permission in Manifest
+ */
+@RunWith(AndroidJUnit4.class)
+public class UsbProfileGroupSettingsManagerTest {
+
+ private static final String TEST_PACKAGE_NAME = "testPkg";
+ @Mock
+ private Context mContext;
+ @Mock
+ private PackageManager mPackageManager;
+ @Mock
+ private ActivityManager mActivityManager;
+ @Mock
+ private UserHandle mUserHandle;
+ @Mock
+ private UsbSettingsManager mUsbSettingsManager;
+ @Mock
+ private UsbHandlerManager mUsbHandlerManager;
+ @Mock
+ private UserManager mUserManager;
+ @Mock
+ private UsbUserSettingsManager mUsbUserSettingsManager;
+ @Mock private Property mProperty;
+ private ActivityManager.RunningAppProcessInfo mRunningAppProcessInfo;
+ private PackageInfo mPackageInfo;
+ private UsbProfileGroupSettingsManager mUsbProfileGroupSettingsManager;
+ private MockitoSession mStaticMockSession;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+
+ mRunningAppProcessInfo = new ActivityManager.RunningAppProcessInfo();
+ mRunningAppProcessInfo.pkgList = new String[]{TEST_PACKAGE_NAME};
+ mPackageInfo = new PackageInfo();
+ mPackageInfo.packageName = TEST_PACKAGE_NAME;
+ mPackageInfo.applicationInfo = Mockito.mock(ApplicationInfo.class);
+
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mContext.getSystemService(ActivityManager.class)).thenReturn(mActivityManager);
+ when(mContext.getResources()).thenReturn(Mockito.mock(Resources.class));
+ when(mContext.createPackageContextAsUser(anyString(), anyInt(), any(UserHandle.class)))
+ .thenReturn(mContext);
+ when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
+
+ mUsbProfileGroupSettingsManager = new UsbProfileGroupSettingsManager(mContext, mUserHandle,
+ mUsbSettingsManager, mUsbHandlerManager);
+
+ mStaticMockSession = ExtendedMockito.mockitoSession()
+ .mockStatic(Flags.class)
+ .strictness(Strictness.WARN)
+ .startMocking();
+
+ when(mPackageManager.getPackageInfo(TEST_PACKAGE_NAME, 0)).thenReturn(mPackageInfo);
+ when(mPackageManager.getProperty(eq(PROPERTY_RESTRICT_USB_OVERLAY_ACTIVITIES),
+ eq(TEST_PACKAGE_NAME))).thenReturn(mProperty);
+ when(mUserManager.getEnabledProfiles(anyInt()))
+ .thenReturn(List.of(Mockito.mock(UserInfo.class)));
+ when(mUsbSettingsManager.getSettingsForUser(anyInt())).thenReturn(mUsbUserSettingsManager);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ mStaticMockSession.finishMocking();
+ }
+
+ @Test
+ public void testDeviceAttached_flagTrueWithoutForegroundActivity_resolveActivityCalled() {
+ when(Flags.allowRestrictionOfOverlayActivities()).thenReturn(true);
+ when(mActivityManager.getRunningAppProcesses()).thenReturn(new ArrayList<>());
+ when(mPackageManager.getPackagesHoldingPermissions(
+ new String[]{android.Manifest.permission.MANAGE_USB},
+ PackageManager.MATCH_SYSTEM_ONLY)).thenReturn(List.of(mPackageInfo));
+ UsbDevice device = Mockito.mock(UsbDevice.class);
+ mUsbProfileGroupSettingsManager.deviceAttached(device);
+ verify(mUsbUserSettingsManager).queryIntentActivities(any(Intent.class));
+ }
+
+ @Test
+ public void testDeviceAttached_noForegroundActivityWithUsbPermission_resolveActivityCalled() {
+ when(Flags.allowRestrictionOfOverlayActivities()).thenReturn(true);
+ when(mActivityManager.getRunningAppProcesses()).thenReturn(List.of(mRunningAppProcessInfo));
+ when(mPackageManager.getPackagesHoldingPermissions(
+ new String[]{android.Manifest.permission.MANAGE_USB},
+ PackageManager.MATCH_SYSTEM_ONLY)).thenReturn(new ArrayList<>());
+ UsbDevice device = Mockito.mock(UsbDevice.class);
+ mUsbProfileGroupSettingsManager.deviceAttached(device);
+ verify(mUsbUserSettingsManager).queryIntentActivities(any(Intent.class));
+ }
+
+ @Test
+ public void testDeviceAttached_foregroundActivityWithManifestField_resolveActivityNotCalled() {
+ when(Flags.allowRestrictionOfOverlayActivities()).thenReturn(true);
+ when(mProperty.getBoolean()).thenReturn(true);
+ when(mActivityManager.getRunningAppProcesses()).thenReturn(List.of(mRunningAppProcessInfo));
+ when(mPackageManager.getPackagesHoldingPermissions(
+ new String[]{android.Manifest.permission.MANAGE_USB},
+ PackageManager.MATCH_SYSTEM_ONLY)).thenReturn(List.of(mPackageInfo));
+ UsbDevice device = Mockito.mock(UsbDevice.class);
+ mUsbProfileGroupSettingsManager.deviceAttached(device);
+ verify(mUsbUserSettingsManager, times(0))
+ .queryIntentActivities(any(Intent.class));
+ }
+
+ @Test
+ public void testDeviceAttached_foregroundActivityWithoutManifestField_resolveActivityCalled() {
+ when(Flags.allowRestrictionOfOverlayActivities()).thenReturn(true);
+ when(mProperty.getBoolean()).thenReturn(false);
+ when(mActivityManager.getRunningAppProcesses()).thenReturn(List.of(mRunningAppProcessInfo));
+ when(mPackageManager.getPackagesHoldingPermissions(
+ new String[]{android.Manifest.permission.MANAGE_USB},
+ PackageManager.MATCH_SYSTEM_ONLY)).thenReturn(List.of(mPackageInfo));
+ UsbDevice device = Mockito.mock(UsbDevice.class);
+ mUsbProfileGroupSettingsManager.deviceAttached(device);
+ verify(mUsbUserSettingsManager).queryIntentActivities(any(Intent.class));
+ }
+
+ @Test
+ public void testDeviceAttached_flagFalseForegroundActivity_resolveActivityCalled() {
+ when(Flags.allowRestrictionOfOverlayActivities()).thenReturn(false);
+ when(mProperty.getBoolean()).thenReturn(true);
+ when(mActivityManager.getRunningAppProcesses()).thenReturn(List.of(mRunningAppProcessInfo));
+ when(mPackageManager.getPackagesHoldingPermissions(
+ new String[]{android.Manifest.permission.MANAGE_USB},
+ PackageManager.MATCH_SYSTEM_ONLY)).thenReturn(List.of(mPackageInfo));
+ UsbDevice device = Mockito.mock(UsbDevice.class);
+ mUsbProfileGroupSettingsManager.deviceAttached(device);
+ verify(mUsbUserSettingsManager).queryIntentActivities(any(Intent.class));
+ }
+}
diff --git a/tests/testables/src/android/testing/TestableLooper.java b/tests/testables/src/android/testing/TestableLooper.java
index 60c25b7..be5c84c 100644
--- a/tests/testables/src/android/testing/TestableLooper.java
+++ b/tests/testables/src/android/testing/TestableLooper.java
@@ -14,6 +14,8 @@
package android.testing;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
@@ -85,6 +87,57 @@
setupQueue(looper);
}
+ /**
+ * Wrap the given runnable so that it will run blocking on the Looper that will be set up for
+ * the given test.
+ * <p>
+ * This method is required to support any TestRule which needs to run setup and/or teardown code
+ * on the TestableLooper. Whether using {@link AndroidTestingRunner} or
+ * {@link TestWithLooperRule}, the TestRule's Statement evaluates on the test instrumentation
+ * thread, rather than the TestableLooper thread, so access to the TestableLooper is required.
+ * However, {@link #get(Object)} will return {@code null} both before and after the inner
+ * statement is evaluated:
+ * <ul>
+ * <li>Before the test {@link #get} returns {@code null} because while the TestableLooperHolder
+ * is accessible in sLoopers, it has not been initialized with an actual TestableLooper yet.
+ * This method's use of the internal LooperFrameworkMethod ensures that all setup and teardown
+ * of the TestableLooper happen as it would for all other wrapped code blocks.
+ * <li>After the test {@link #get} can return {@code null} because many tests call
+ * {@link #remove} in the teardown method. The fact that this method returns a runnable allows
+ * it to be called before the test (when the TestableLooperHolder is still in sLoopers), and
+ * then executed as teardown after the test.
+ * </ul>
+ *
+ * @param test the test instance (just like passed to {@link #get(Object)})
+ * @param runnable the operation that should eventually be run on the TestableLooper
+ * @return a runnable that will block the thread on which it is called until the given runnable
+ * is finished. Will be {@code null} if there is no looper for the given test.
+ * @hide
+ */
+ @Nullable
+ public static RunnableWithException wrapWithRunBlocking(
+ Object test, @NonNull RunnableWithException runnable) {
+ TestableLooperHolder looperHolder = sLoopers.get(test);
+ if (looperHolder == null) {
+ return null;
+ }
+ try {
+ FrameworkMethod base = new FrameworkMethod(runnable.getClass().getMethod("run"));
+ LooperFrameworkMethod wrapped = new LooperFrameworkMethod(base, looperHolder);
+ return () -> {
+ try {
+ wrapped.invokeExplosively(runnable);
+ } catch (RuntimeException | Error e) {
+ throw e;
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ };
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
public Looper getLooper() {
return mLooper;
}
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt
index 97e09b8..06eeb47c 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGen.kt
@@ -49,6 +49,7 @@
class HostStubGen(val options: HostStubGenOptions) {
fun run() {
val errors = HostStubGenErrors()
+ val stats = HostStubGenStats()
// Load all classes.
val allClasses = loadClassStructures(options.inJar.get)
@@ -80,7 +81,14 @@
options.enableClassChecker.get,
allClasses,
errors,
+ stats,
)
+
+ // Dump statistics, if specified.
+ options.statsFile.ifSet {
+ PrintWriter(it).use { pw -> stats.dump(pw) }
+ log.i("Dump file created at $it")
+ }
}
/**
@@ -237,6 +245,7 @@
enableChecker: Boolean,
classes: ClassNodes,
errors: HostStubGenErrors,
+ stats: HostStubGenStats,
) {
log.i("Converting %s into [stub: %s, impl: %s] ...", inJar, outStubJar, outImplJar)
log.i("ASM CheckClassAdapter is %s", if (enableChecker) "enabled" else "disabled")
@@ -254,7 +263,8 @@
while (inEntries.hasMoreElements()) {
val entry = inEntries.nextElement()
convertSingleEntry(inZip, entry, stubOutStream, implOutStream,
- filter, packageRedirector, enableChecker, classes, errors)
+ filter, packageRedirector, enableChecker, classes, errors,
+ stats)
}
log.i("Converted all entries.")
}
@@ -287,6 +297,7 @@
enableChecker: Boolean,
classes: ClassNodes,
errors: HostStubGenErrors,
+ stats: HostStubGenStats,
) {
log.d("Entry: %s", entry.name)
log.withIndent {
@@ -300,7 +311,7 @@
// If it's a class, convert it.
if (name.endsWith(".class")) {
processSingleClass(inZip, entry, stubOutStream, implOutStream, filter,
- packageRedirector, enableChecker, classes, errors)
+ packageRedirector, enableChecker, classes, errors, stats)
return
}
@@ -354,6 +365,7 @@
enableChecker: Boolean,
classes: ClassNodes,
errors: HostStubGenErrors,
+ stats: HostStubGenStats,
) {
val classInternalName = entry.name.replaceFirst("\\.class$".toRegex(), "")
val classPolicy = filter.getPolicyForClass(classInternalName)
@@ -370,7 +382,7 @@
stubOutStream.putNextEntry(newEntry)
convertClass(classInternalName, /*forImpl=*/false, bis,
stubOutStream, filter, packageRedirector, enableChecker, classes,
- errors)
+ errors, stats)
stubOutStream.closeEntry()
}
}
@@ -383,7 +395,7 @@
implOutStream.putNextEntry(newEntry)
convertClass(classInternalName, /*forImpl=*/true, bis,
implOutStream, filter, packageRedirector, enableChecker, classes,
- errors)
+ errors, stats)
implOutStream.closeEntry()
}
}
@@ -403,6 +415,7 @@
enableChecker: Boolean,
classes: ClassNodes,
errors: HostStubGenErrors,
+ stats: HostStubGenStats,
) {
val cr = ClassReader(input)
@@ -420,6 +433,7 @@
enablePostTrace = options.enablePostTrace.get,
enableNonStubMethodCallDetection = options.enableNonStubMethodCallDetection.get,
errors = errors,
+ stats = stats,
)
outVisitor = BaseAdapter.getVisitor(classInternalName, classes, outVisitor, filter,
packageRedirector, forImpl, visitorOptions)
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt
index d2ead18..9f5d524 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenOptions.kt
@@ -108,6 +108,8 @@
var enablePostTrace: SetOnce<Boolean> = SetOnce(false),
var enableNonStubMethodCallDetection: SetOnce<Boolean> = SetOnce(false),
+
+ var statsFile: SetOnce<String?> = SetOnce(null),
) {
companion object {
@@ -252,6 +254,8 @@
"--verbose-log" -> setLogFile(LogLevel.Verbose, nextArg())
"--debug-log" -> setLogFile(LogLevel.Debug, nextArg())
+ "--stats-file" -> ret.statsFile.setNextStringArg()
+
else -> throw ArgumentsException("Unknown option: $arg")
}
} catch (e: SetOnce.SetMoreThanOnceException) {
@@ -387,6 +391,7 @@
enablePreTrace=$enablePreTrace,
enablePostTrace=$enablePostTrace,
enableNonStubMethodCallDetection=$enableNonStubMethodCallDetection,
+ statsFile=$statsFile,
}
""".trimIndent()
}
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenStats.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenStats.kt
new file mode 100644
index 0000000..fe4072f
--- /dev/null
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/HostStubGenStats.kt
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.hoststubgen
+
+import com.android.hoststubgen.asm.toHumanReadableClassName
+import com.android.hoststubgen.filters.FilterPolicyWithReason
+import java.io.PrintWriter
+
+open class HostStubGenStats {
+ data class Stats(
+ var supported: Int = 0,
+ var total: Int = 0,
+ val children: MutableMap<String, Stats> = mutableMapOf<String, Stats>(),
+ )
+
+ private val stats = mutableMapOf<String, Stats>()
+
+ fun onVisitPolicyForMethod(fullClassName: String, policy: FilterPolicyWithReason) {
+ if (policy.isIgnoredForStats) return
+
+ val packageName = resolvePackageName(fullClassName)
+ val className = resolveClassName(fullClassName)
+
+ val packageStats = stats.getOrPut(packageName) { Stats() }
+ val classStats = packageStats.children.getOrPut(className) { Stats() }
+
+ if (policy.policy.isSupported) {
+ packageStats.supported += 1
+ classStats.supported += 1
+ }
+ packageStats.total += 1
+ classStats.total += 1
+ }
+
+ fun dump(pw: PrintWriter) {
+ pw.printf("PackageName,ClassName,SupportedMethods,TotalMethods\n")
+ stats.forEach { (packageName, packageStats) ->
+ if (packageStats.supported > 0) {
+ packageStats.children.forEach { (className, classStats) ->
+ pw.printf("%s,%s,%d,%d\n", packageName, className,
+ classStats.supported, classStats.total)
+ }
+ }
+ }
+ }
+
+ private fun resolvePackageName(fullClassName: String): String {
+ val start = fullClassName.lastIndexOf('/')
+ return fullClassName.substring(0, start).toHumanReadableClassName()
+ }
+
+ private fun resolveClassName(fullClassName: String): String {
+ val start = fullClassName.lastIndexOf('/')
+ val end = fullClassName.indexOf('$')
+ if (end == -1) {
+ return fullClassName.substring(start + 1)
+ } else {
+ return fullClassName.substring(start + 1, end)
+ }
+ }
+}
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicy.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicy.kt
index 9317996..4d21106 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicy.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicy.kt
@@ -111,6 +111,16 @@
}
}
+ /** Returns whether a policy is considered supported. */
+ val isSupported: Boolean
+ get() {
+ return when (this) {
+ // TODO: handle native method with no substitution as being unsupported
+ Stub, StubClass, Keep, KeepClass, SubstituteAndStub, SubstituteAndKeep -> true
+ else -> false
+ }
+ }
+
fun getSubstitutionBasePolicy(): FilterPolicy {
return when (this) {
SubstituteAndKeep -> Keep
@@ -136,4 +146,4 @@
fun withReason(reason: String): FilterPolicyWithReason {
return FilterPolicyWithReason(this, reason)
}
-}
\ No newline at end of file
+}
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicyWithReason.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicyWithReason.kt
index b64a2f5..53eb5a8 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicyWithReason.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/FilterPolicyWithReason.kt
@@ -63,4 +63,15 @@
override fun toString(): String {
return "[$policy - reason: $reason]"
}
-}
\ No newline at end of file
+
+ /** Returns whether this policy should be ignored for stats. */
+ val isIgnoredForStats: Boolean
+ get() {
+ return reason.contains("anonymous-inner-class")
+ || reason.contains("is-annotation")
+ || reason.contains("is-enum")
+ || reason.contains("is-synthetic-method")
+ || reason.contains("special-class")
+ || reason.contains("substitute-from")
+ }
+}
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/ImplicitOutputFilter.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/ImplicitOutputFilter.kt
index ea7d1d0..78b13fd 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/ImplicitOutputFilter.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/ImplicitOutputFilter.kt
@@ -119,14 +119,14 @@
if (cn.isEnum()) {
mn?.let { mn ->
if (isAutoGeneratedEnumMember(mn)) {
- return memberPolicy.withReason(classPolicy.reason).wrapReason("enum")
+ return memberPolicy.withReason(classPolicy.reason).wrapReason("is-enum")
}
}
}
// Keep (or stub) all members of annotations.
if (cn.isAnnotation()) {
- return memberPolicy.withReason(classPolicy.reason).wrapReason("annotation")
+ return memberPolicy.withReason(classPolicy.reason).wrapReason("is-annotation")
}
mn?.let {
@@ -134,7 +134,7 @@
// For synthetic methods (such as lambdas), let's just inherit the class's
// policy.
return memberPolicy.withReason(classPolicy.reason).wrapReason(
- "synthetic method")
+ "is-synthetic-method")
}
}
}
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/TextFileFilterPolicyParser.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/TextFileFilterPolicyParser.kt
index 7fdd944..6ad83fb 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/TextFileFilterPolicyParser.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/filters/TextFileFilterPolicyParser.kt
@@ -132,23 +132,24 @@
throw ParseException(
"Policy for AIDL classes already defined")
}
- aidlPolicy = policy.withReason("$FILTER_REASON (AIDL)")
+ aidlPolicy = policy.withReason(
+ "$FILTER_REASON (special-class AIDL)")
}
SpecialClass.FeatureFlags -> {
if (featureFlagsPolicy != null) {
throw ParseException(
"Policy for feature flags already defined")
}
- featureFlagsPolicy =
- policy.withReason("$FILTER_REASON (feature flags)")
+ featureFlagsPolicy = policy.withReason(
+ "$FILTER_REASON (special-class feature flags)")
}
SpecialClass.Sysprops -> {
if (syspropsPolicy != null) {
throw ParseException(
"Policy for sysprops already defined")
}
- syspropsPolicy =
- policy.withReason("$FILTER_REASON (sysprops)")
+ syspropsPolicy = policy.withReason(
+ "$FILTER_REASON (special-class sysprops)")
}
}
}
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/BaseAdapter.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/BaseAdapter.kt
index 21cfd4b..c20aa8b 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/BaseAdapter.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/BaseAdapter.kt
@@ -16,6 +16,7 @@
package com.android.hoststubgen.visitors
import com.android.hoststubgen.HostStubGenErrors
+import com.android.hoststubgen.HostStubGenStats
import com.android.hoststubgen.LogLevel
import com.android.hoststubgen.asm.ClassNodes
import com.android.hoststubgen.asm.UnifiedVisitor
@@ -50,6 +51,7 @@
*/
data class Options (
val errors: HostStubGenErrors,
+ val stats: HostStubGenStats,
val enablePreTrace: Boolean,
val enablePostTrace: Boolean,
val enableNonStubMethodCallDetection: Boolean,
diff --git a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/ImplGeneratingAdapter.kt b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/ImplGeneratingAdapter.kt
index 416b782..beca945 100644
--- a/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/ImplGeneratingAdapter.kt
+++ b/tools/hoststubgen/hoststubgen/src/com/android/hoststubgen/visitors/ImplGeneratingAdapter.kt
@@ -141,6 +141,11 @@
substituted: Boolean,
superVisitor: MethodVisitor?,
): MethodVisitor? {
+ // Record statistics about visiting this method when visible.
+ if ((access and Opcodes.ACC_PRIVATE) == 0) {
+ options.stats.onVisitPolicyForMethod(currentClassName, policy)
+ }
+
// Inject method log, if needed.
var innerVisitor = superVisitor